简体   繁体   English

如何在Android中每2个字符后将特殊符号连接为冒号

[英]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. 我想连接或附加特殊字符作为冒号在String中每2个字符后。

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. 所以我的问题是如何在android中实现这一点。

Thanks in advance. 提前致谢。

In Kotlin use chunked(2) to split the String every 2 chars and rejoin with joinToString(":") : 在Kotlin中使用chunked(2)每2个字符拆分String并使用joinToString(":")重新加入:

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

will print 将打印

AA:BB:CC:DD:EE:FF

Use a StringBuilder : 使用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();

You can try below code, if you want to do without Math class functions. 如果您不想使用Math类函数,可以尝试下面的代码。

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 **":" a%2 == 1 ** ==>此条件语句用于附加**“:”
  2. a < abc.length() -1 ==> this conditional statement is used not to add ":" a <abc.length() - 1 ==>此条件语句用于不添加“:”

in last entry. 在最后一个条目。 Hope this makes sense. 希望这是有道理的。 If you found any problem please let me know. 如果您发现任何问题,请告诉我。

Here is the Kotlin way. 这是Kotlin的方式。 without StringBuilder 没有StringBuilder

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

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. 你可以将String.splitString.joinTextUtils.join(":", someList)用于android)首先在每个第二个字符串中拆分字符串并使用你想要的分隔符连接它。 Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM