Search code examples
javaandroidstringkotlinstringbuilder

How to concatenate Special symbol as colon after every 2 character in Android


I want to concatenate or append special character as colon : after an every 2 character in String.

For Example: Original String are as follow:

String abc =AABBCCDDEEFF;

After concatenate or append colon are as follow:

  String abc =AA:BB:CC:DD:EE:FF;

So my question is how we can achieve this in android.

Thanks in advance.


Solution

  • You can try below code, if you want to do without Math class functions.

    StringBuilder stringBuilder = new StringBuilder();
        for (int a =0; a < abc.length(); a++) {
            stringBuilder.append(abc.charAt(a));
            if (a % 2 == 1 && a < abc.length() -1)
                stringBuilder.append(":");
        }
    

    Here

    1. a % 2 == 1 ** ==> this conditional statement is used to append **":"
    2. a < abc.length() -1 ==> this conditional statement is used not to add ":"

    in last entry. Hope this makes sense. If you found any problem please let me know.