0

I have a number String like "1234567890".

I need to format this String into "1234 5678 90". (The blank spaces are SPACE character) Could somebody tell me on how to do this in java?

Thanks

4

6 回答 6

2

假设您的字符串长度相同:

String s1 = "1234567890";
String s2 = s1.substring(0, 3) + " " + s1.substring(4, 7) + " " + s1.substring(8, 9);
于 2013-04-22T13:47:30.733 回答
1

您可以StringBuilder用于性能:

StringBuilder builder = new StringBuilder("1234567890");
builder.insert(4, ' ').insert(9, ' ');
String formattedString = builder.toString();

给你

1234 5678 90
于 2013-04-22T14:14:30.000 回答
1
   StringBuilder sb= new StringBuilder("1234567890");
   sb.insert(4, ' ').insert(9, ' ');
   String output= sb.toString();
于 2013-04-22T13:46:59.607 回答
1

基于正则表达式的版本

     String s = "1234567890";
     s = s.replaceAll("(\\d+)(\\d{2})", "$1 $2");
     while(s.matches("\\d+\\d{4} \\d+")) {
         s = s.replaceAll("(\\d+)(\\d{4} \\d+)", "$1 $2");
     }
     System.out.println(s);

输出

1234 5678 90

于 2013-04-22T13:59:04.080 回答
0

尝试使用java.text.MessageFormat.

public static void main(String[] args) {
    String phoneRawString = "1234567890";

    java.text.MessageFormat phoneMsgFmt = new java.text.MessageFormat(
            "{0} {1} {2}");
    // suposing a grouping of 4-4-2
    String[] phoneNumArr = { phoneRawString.substring(0, 4),
            phoneRawString.substring(4, 8), phoneRawString.substring(8) };

    System.out.println(phoneMsgFmt.format(phoneNumArr));
}

输出:

1234 5678 90

使用正则表达式的另一种方法:

long phoneNum = 1234567890L;
String result = String.valueOf(phoneNum).replaceFirst("(\\d{4})(\\d{4})(\\d+)", "$1 $2 $3");
System.out.println(result);
于 2013-04-22T14:07:38.103 回答
0
    String input = "1234567890";
    Formatter f = new Formatter(new StringBuilder(), Locale.UK);
    String res = f.format("%s%5s%3s", input.substring(0, 4), input.substring(4, 8), input.substring(8, 10)).toString();
    System.out.println(res);
于 2013-04-22T14:32:31.680 回答