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

我想将特殊字符连接或附加为冒号在字符串中的每 2 个字符之后。

例如:原始字符串如下:

String abc =AABBCCDDEEFF;

连接或附加冒号后如下:

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

所以我的问题是我们如何在android中实现这一点。

提前致谢。


沧海一幻觉
浏览 315回答 3
3回答

收到一只叮咚

在 Kotlinchunked(2)中,用于拆分String每 2 个字符并重新加入joinToString(":"):val str = "AABBCCDDEEFF"val newstr = str.chunked(2).joinToString(":")println(newstr)将打印AA:BB:CC:DD:EE:FF

慕神8447489

如果您不想使用 Math 类函数,可以尝试下面的代码。StringBuilder stringBuilder = new StringBuilder();&nbsp; &nbsp; for (int a =0; a < abc.length(); a++) {&nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.append(abc.charAt(a));&nbsp; &nbsp; &nbsp; &nbsp; if (a % 2 == 1 && a < abc.length() -1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.append(":");&nbsp; &nbsp; }这里a % 2 == 1 ** ==> 此条件语句用于附加 **":"a < abc.length() -1&nbsp;==> 这个条件语句用来不加“:”在最后一个条目中。希望这是有道理的。如果您发现任何问题,请告诉我。

RISEBY

使用StringBuilder:StringBuilder sb = new StringBuilder(abc.length() * 3 / 2);String delim = "";for (int i = 0; i < abc.length(); i += 2) {&nbsp; sb.append(delim);&nbsp; sb.append(abc, i, Math.min(i + 2, abc.length()));&nbsp; delim = ":";}String newAbc = sb.toString();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java