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
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
假设您的字符串长度相同:
String s1 = "1234567890";
String s2 = s1.substring(0, 3) + " " + s1.substring(4, 7) + " " + s1.substring(8, 9);
您可以StringBuilder
用于性能:
StringBuilder builder = new StringBuilder("1234567890");
builder.insert(4, ' ').insert(9, ' ');
String formattedString = builder.toString();
给你
1234 5678 90
StringBuilder sb= new StringBuilder("1234567890");
sb.insert(4, ' ').insert(9, ' ');
String output= sb.toString();
基于正则表达式的版本
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
尝试使用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);
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);