String Manipulation insert a character every 4th character [duplicate]

北城以北 提交于 2020-08-10 19:01:12

问题


In Android if I have an edit text and the user entered 123456789012, how could I get the program to insert a dash every 4th character. ie: 1234-5678-9012?

I guess you need to say something along the lines of:- a=Characters 1~4, b=Characters 5~8, c=Characters 9-12, Result = a + "-" + b + "-" + c. But I am unsure of how that would look in Android.

Many thanks for any help.


回答1:


String s = "123456789012";
String s1 = s.substring(0, 4);
String s2 = s.substring(4, 8);
String s3 = s.substring(8, 12);

String dashedString = s1 + "-" + s2 + "-" + s3;
//String.format is extremely slow. Just concatenate them, as above.

substring() Reference




回答2:


Or another alternative way using a StringBuilder rather than to split the string in multiple parts and then join them :

String original = "123456789012";
int interval = 4;
char separator = '-';

StringBuilder sb = new StringBuilder(original);

for(int i = 0; i < original.length() / interval; i++) {
    sb.insert(((i + 1) * interval) + i, separator);
}

String withDashes = sb.toString();



回答3:


Alternative way:

String original = "123456789012";
int dashInterval = 4;
String withDashes = original.substring(0, dashInterval);
for (int i = dashInterval; i < original.length(); i += dashInterval) {
    withDashes += "-" + original.substring(i, i + dashInterval);
}

return withDashes;

If you needed to pass strings with lengths that were not multiples of the dashInterval you'd have to write an extra bit to handle that to prevent index out of bounds nonsense.



来源:https://stackoverflow.com/questions/4169699/string-manipulation-insert-a-character-every-4th-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!