How to add characters to a string in specific indexes?

I have a string formed with 6 letters eg: "abcdef". I need to add "." every two characters so it would be like this: "". 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:)


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);

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

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

Try regexp:




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


Need Your Help

How to make a simple keypad on java to input in JTextFields efficiently?

java jtextfield keypad

I am working on a keypad on java that will be used to input data in two JTextField (x & y). And Once the user clicks "Enter", It should evaluate the difference of x and y. Do I have to add bu...