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

发布于 2024-10-02 13:56:54 字数 256 浏览 3 评论 0原文

在 Android 中,如果我有一个编辑文本并且用户输入 123456789012,我怎样才能让程序每 4 个字符插入一个破折号。 即:1234-5678-9012

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

非常感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奢华的一滴泪 2024-10-09 13:56:54
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() 参考

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

丿*梦醉红颜 2024-10-09 13:56:54

或者使用 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();

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();
三生一梦 2024-10-09 13:56:54

替代方法:

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;

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文