4

I need your help to turn a String like 12345678 into 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

2
  • the input is always 8 digits. Is it more expensive to use a regular expression? I tried it with regular expressions because I think it is more effective than concatenation. Sorry, I'm new, I'm trying to do it in the best way. Commented Jan 13, 2017 at 19:00
  • 2
    Using regex will surely be more expensive than simple substring here. Commented Jan 13, 2017 at 19:03

3 Answers 3

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:

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.

Output:

1234.56.78
Sign up to request clarification or add additional context in comments.

3 Comments

You don't really need to use StringBuilder, pretty sure javac will automatically decide to use it.
@SameerPuri I'm sorry, I don't fully understand your comment. If you are saying that we can simply use + for the concatenation and it will be optimized later by the compiler then it's true. But it's even better if you take care of things yourself rather than leaving it on the compiler. Well, that's my opinion which might differ from what other people think.
Yes that's what I meant -- just for simplicity's sake since it would be done by javac anyways. You do have a point though, that behavior could change in the future creating unexpected results.
3

Use a single replaceAll() method with updated regex otherwise the second replaceAll() call will replace including the first four digits.

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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.