在字符串之前添加空格 - 不像我想象的那样运作

时间:2013-03-05 23:12:33

标签: java concatenation

我熟悉连接,这是一个简单的概念。我正在尝试做什么 - 使用简单的子串方法对齐几个数字。这就是我所拥有的,希望能够更好地解释它:

String a1 = "    " + "" + a;
String e1 = "    " + "" + e;
String i1 = "    " + "" + i;
String o1 = "    " + "" + o;
String u1 = "    " + "" + u;

System.out.println ("The file contained:");
System.out.println ("A: " +  a1.substring(4));
System.out.println ("E: " +  e1.substring(4));
System.out.println ("I: " +  i1.substring(4));
System.out.println ("O: " +  o1.substring(4));
System.out.println ("U: " +  u1.substring(4));

我省略了剩下的代码,因为它与我的问题无关(并且工作正常)。

我希望这样做可以将a,e,i,o和u与4个'空格'连接起来。当我运行程序时,在a,e,i,o或u之前没有任何空格的迹象。

感谢任何帮助或意见。

编辑*:我应该澄清一下。我想要字符串的最后4个字符,因此a1.substring(4);.

编辑2:我是个白痴。这对我来说是一个非常简单的忽视。正确使用子字符串右对齐的代码:

     String a1 = "    " + a;
     String e1 = "    " + e;
     String i1 = "    " + i;
     String o1 = "    " + o;
     String u1 = "    " + u;
  System.out.println ("The file contained:");
  System.out.println ("A: " +  a1.substring(a1.length() - 4));
  System.out.println ("E: " +  e1.substring(e1.length() - 4));
  System.out.println ("I: " +  i1.substring(i1.length() - 4));
  System.out.println ("O: " +  o1.substring(o1.length() - 4));
  System.out.println ("U: " +  u1.substring(u1.length() - 4));

3 个答案:

答案 0 :(得分:5)

如果你想做的只是对齐整数,你可以用printf这样做:

int a = 10;
int b = 100;
System.out.printf("A:%20d\n", a);
System.out.printf("B:%20d\n", b);

输出:

A:                  10
B:                 100

编辑后编辑。

取字符串的最后四个字符

s.substring(s.length()-4)

答案 1 :(得分:3)

如果您需要使用空格,您可以这样做:

String a1 = "    " + a;
String e1 = "    " + e;
String i1 = "    " + i;
String o1 = "    " + o;
String u1 = "    " + u;

System.out.println ("The file contained:");
System.out.println ("A: " +  a1);
System.out.println ("E: " +  e1);
System.out.println ("I: " +  i1);
System.out.println ("O: " +  o1);
System.out.println ("U: " +  u1);

答案 2 :(得分:1)

尝试

String a1 = "    " + "" + a;
String e1 = "    " + "" + e;
String i1 = "    " + "" + i;
String o1 = "    " + "" + o;
String u1 = "    " + "" + u;

System.out.println ("The file contained:");
System.out.println ("A: " +  a1.substring(0, 4));
System.out.println ("E: " +  e1.substring(0, 4));
System.out.println ("I: " +  i1.substring(0, 4));
System.out.println ("O: " +  o1.substring(0, 4));
System.out.println ("U: " +  u1.substring(0, 4));

substring(4)准确打印字符串的第4个索引 substring(0,4)从索引0打印到第4个。