3

I have a string formed with 6 letters eg: "abcdef". I need to add "." every two characters so it would be like this: "ab.cd.ef". I'm working in java, I tried this:

private String FormatAddress(String sourceAddress) {
    char[] sourceAddressFormatted = new char[8];
    sourceAddress.getChars(0, 1, sourceAddressFormatted, 0);
    sourceAddress += ".";
    sourceAddress.getChars(2, 3, sourceAddressFormatted, 3);
    sourceAddress += ".";
    sourceAddress.getChars(4, 5, sourceAddressFormatted, 6);
    String s = new String(sourceAddressFormatted);
    return s;
}

But i received strange values such as [C@2723b6.

Thanks in advance:)

1
  • For better help sooner, post an SSCCE. Commented May 3, 2013 at 8:37

4 Answers 4

5

Try regexp:

Input:

abcdef

Code:

System.out.println("abcdef".replaceAll(".{2}(?!$)", "$0."));

Output:

ab.cd.ef
Sign up to request clarification or add additional context in comments.

Comments

1

You should fix it as

    String sourceAddress = "abcdef";
    String s = sourceAddress.substring(0, 2);
    s += ".";
    s += sourceAddress.substring(2, 4);
    s += ".";
    s += sourceAddress.substring(4, 6);
    System.out.println(s);

You also can do the same with regex, it's a one line solution

    String s = sourceAddress.replaceAll("(\\w\\w)(?=\\w\\w)", "$1.");
    System.out.println(s);

Comments

0
private String formatAddress(String sourceAddress) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < sourceAddress.length(); i+=2) {
        sb.append(sourceAddress.substring(i, i+2));
        if (i != sourceAddress.length()-1) {
            sb.append('.');
        }
    }
    return sb.toString();
}

Comments

0

Try this:

String result="";
String str ="abcdef";
for(int i =2; i<str.length(); i=i+2){
     result = result + str.substring(i-2 , i) + ".";
}
result = result + str.substring(str.length()-2);

1 Comment

The last two letters won't be added this way.

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.