I need your help to turn a String like 12345678
into 1234.56.78
我需要你的帮助把像12345678这样的字符串变成1234.56.78
[FOUR DIGITS].[TWO DIGITS].[TWO DIGITS]
My code:
String s1 = "12345678";
s1 = s1.replaceAll("(\\d{4})(\\d+)", "$1.$2").replaceAll("(\\d{2})(\\d+)", "$1.$2");
System.out.println(s1);
But the result is 12.34.56.78
但结果是12.34.56.78
3 个解决方案
#1
3
If you are sure that you'll always have the input in the same format then you can simply use a StringBuilder
and do something like this:
如果您确定您将始终以相同的格式输入,那么您可以简单地使用StringBuilder并执行以下操作:
String input = "12345678";
String output = new StringBuilder().append(input.substring(0, 4))
.append(".").append(input.substring(4, 6)).append(".")
.append(input.substring(6)).toString();
System.out.println(output);
This code creates a new String by appending the dots to the sub-strings at the specified locations.
此代码通过将点附加到指定位置的子字符串来创建新的String。
Output:
1234.56.78
#2
3
Use a single replaceAll()
method with updated regex otherwise the second replaceAll()
call will replace including the first four digits.
使用单个replaceAll()方法和更新的正则表达式,否则第二个replaceAll()调用将替换包括前四个数字。
System.out.println(s1.replaceAll("(\\d{4})(\\d{2})(\\d+)", "$1.$2.$3")
#3
2
This puts dots after every pair of chars, except the first pair:
这会在每对字符之后加上点,第一对除外:
str = str.replaceAll("(^....)|(..)", "$1$2.");
This works for any length string, including odd lengths.
这适用于任何长度的字符串,包括奇数长度。
For example
"1234567890123" --> "1234.56.78.90.12.3"
#1
3
If you are sure that you'll always have the input in the same format then you can simply use a StringBuilder
and do something like this:
如果您确定您将始终以相同的格式输入,那么您可以简单地使用StringBuilder并执行以下操作:
String input = "12345678";
String output = new StringBuilder().append(input.substring(0, 4))
.append(".").append(input.substring(4, 6)).append(".")
.append(input.substring(6)).toString();
System.out.println(output);
This code creates a new String by appending the dots to the sub-strings at the specified locations.
此代码通过将点附加到指定位置的子字符串来创建新的String。
Output:
1234.56.78
#2
3
Use a single replaceAll()
method with updated regex otherwise the second replaceAll()
call will replace including the first four digits.
使用单个replaceAll()方法和更新的正则表达式,否则第二个replaceAll()调用将替换包括前四个数字。
System.out.println(s1.replaceAll("(\\d{4})(\\d{2})(\\d+)", "$1.$2.$3")
#3
2
This puts dots after every pair of chars, except the first pair:
这会在每对字符之后加上点,第一对除外:
str = str.replaceAll("(^....)|(..)", "$1$2.");
This works for any length string, including odd lengths.
这适用于任何长度的字符串,包括奇数长度。
For example
"1234567890123" --> "1234.56.78.90.12.3"