Add a character to the middle of a line

I need your help to turn String as 12345678into1234.56.78

[FOUR DIGITS].[TWO DIGITS].[TWO DIGITS]

My code is:

String s1 = "12345678";
s1 = s1.replaceAll("(\\d{4})(\\d+)", "$1.$2").replaceAll("(\\d{2})(\\d+)", "$1.$2");
System.out.println(s1);

But the result 12.34.56.78

+4
source share
3 answers

If you are sure that you will always have input in the same format, you can just use StringBuilderand do something like this:

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 line by adding dots to the substrings in the specified places.

Conclusion:

1234.56.78
+3
source

Use one method replaceAll()with an updated regular expression, otherwise the second replaceAll()will replace, including the first four digits.

System.out.println(s1.replaceAll("(\\d{4})(\\d{2})(\\d+)", "$1.$2.$3")
+3
source

, :

str = str.replaceAll("(^....)|(..)", "$1$2.");

, .

"1234567890123" --> "1234.56.78.90.12.3"
+2

Source: https://habr.com/ru/post/1666746/


All Articles