2

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.

Nitin Karande
  • 1,280
  • 14
  • 33

5 Answers5

6

In Kotlin use chunked(2) to split the String every 2 chars and rejoin with joinToString(":"):

val str = "AABBCCDDEEFF"
val newstr = str.chunked(2).joinToString(":")
println(newstr)

will print

AA:BB:CC:DD:EE:FF
forpas
  • 160,666
  • 10
  • 38
  • 76
3

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.

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58
2

Use a StringBuilder:

StringBuilder sb = new StringBuilder(abc.length() * 3 / 2);
String delim = "";
for (int i = 0; i < abc.length(); i += 2) {
  sb.append(delim);
  sb.append(abc, i, Math.min(i + 2, abc.length()));
  delim = ":";
}
String newAbc = sb.toString();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

Here is the Kotlin way. without StringBuilder

val newString: String = abc.toCharArray().mapIndexed { index, c ->
            if (index % 2 == 1 && index < abc.length - 1) {
                "$c:"
            } else {
                c
            }
        }.joinToString("")
Milind Mevada
  • 3,145
  • 1
  • 14
  • 22
1

You can combine String.split and String.join (TextUtils.join(":", someList) for android) to first split the string at each second char and join it using the delimiter you want. Example:

String abc = "AABBCCDDEEFF";
String def = String.join(":", abc.split("(?<=\\G.{2})"));
System.out.println(def);
//AA:BB:CC:DD:EE:FF
Eritrean
  • 15,851
  • 3
  • 22
  • 28