java 字符串操作每第 4 个字符插入一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4169699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:09:40  来源:igfitidea点击:

String Manipulation insert a character every 4th character

javaandroidstringconcatenationandroid-edittext

提问by Entropy1024

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?

在 Android 中,如果我有一个编辑文本并且用户输入了 123456789012,我怎么能让程序每 4 个字符插入一个破折号。即: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.

我想你需要说一些类似的东西:- a=Characters 1~4, b=Characters 5~8, c=Characters 9-12, Result = a + "-" + b + "-" + c。但我不确定这在 Android 中会是什么样子。

Many thanks for any help.

非常感谢您的帮助。

回答by Evan Mulawski

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

substring()参考

回答by Marc Wrobel

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

或者使用 StringBuilder 的另一种替代方法,而不是将字符串拆分为多个部分然后加入它们:

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();

回答by matt burns

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.

如果您需要传递长度不是 dashInterval 倍数的字符串,您必须编写一个额外的位来处理它以防止索引越界废话。