0

一种如何格式化以下内容:

由此:

1: My street
2: 1232321
3: Hello there world!
4: A really really really long word!

对此:

1:                           My street
2:                             1232321
3:                  Hello there world!
4:   A really really really long word!

我认为它与 String.format() 和其中的一堆随机字符有关!

4

1 回答 1

3

您可以先将字符串拆分为 get1:My Street单独,然后对其进行格式化:-

String str = "1: My street";
String str2 = "3: Hello there world!";

String[] arr = str.split("(?<=:) ");
String[] arr2 = str2.split("(?<=:) ");

System.out.printf("%s%30s\n", arr[0], arr[1]);
System.out.printf("%s%30s", arr2[0], arr2[1]);

输出 : -

1:                     My street
3:            Hello there world!

您也可以使用String#substring方法来执行此操作,以分别获取这两个部分。

System.out.printf("%s%30s\n", str.substring(0, 2), str.substring(3));
于 2012-12-01T18:41:20.063 回答