在 iPhone 中格式化字符串
我需要在字符串中每 4 个字符后添加空格。例如,如果字符串是 aaaaaaaa
,我需要将其格式化为 aaaa aaaa
。我尝试了以下代码,但它对我不起作用。
NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString];
int count = [formattedString length];
for (int i = 0; i<count; i++) {
if ( i %4 == 0) {
[currentFormattedString insertString:@" " atIndex:i];
}
}
谁能帮我解决这个问题吗?
I need to add space after every 4 characters in a string.. For example if the string is aaaaaaaa
, i need to format it as aaaa aaaa
. I tried the following code, but it doesn't work for me.
NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString];
int count = [formattedString length];
for (int i = 0; i<count; i++) {
if ( i %4 == 0) {
[currentFormattedString insertString:@" " atIndex:i];
}
}
Can anyone help me with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您还没有说明什么不适用于您的代码,因此很难确切地知道该回答什么。作为提示 - 在以后的问题中不要只说“它不起作用”,而是要说明什么不起作用以及它如何不起作用。但是...
您正在插入一个空格,但您没有在索引值中考虑到这一点。所以,假设你的 formattedString 是 aaaaaaaaaaaaaaaa
第一次通过循环时,您将到达第 4 个位置并在 i=4
aaaa aaaaaaaaaaaa
处插入一个空格。现在,下次您插入空格时,i 将是 8。但是 currentFormattedString 中的第 8 个位置不是你认为会是
aaaa aaa aaaaaaaaa
下次会是另外 4 个字符,但仍然不是你认为的
aaaa aaa aa aaaaaaa
等等
您必须考虑插入的空间,这会影响偏移值。
You haven't said what isn't working with your code, so it's hard to know exactly what to answer. As a tip - in future questions don't just say "it isn't working", but state WHAT isn't working and HOW it isn't working. However...
You are inserting a space, but you are not then accounting for this in your index value. So, suppose your formattedString is aaaaaaaaaaaaaaaa
The first time through your loop, you will get to the 4th position and insert a space at i=4
aaaa aaaaaaaaaaaa
Now the next time you get to insert a space, i will be 8. But the 8th position in your currentFormattedString isn't where you think it will be
aaaa aaa aaaaaaaaa
Next time it will be another 4 characters along which still isn't where you think
aaaa aaa aa aaaaaaa
And so on
You have to take into account the inserted space which will affect the offset value.
我发现以下内容将字符串格式化为电话号码格式,但看起来您可以轻松更改它以支持其他格式
电话号码字符串格式
I found the following which formats a string to a telephone number format, but it looks like you could easily change it to support other formats
Telephone number string formatting
尼克·布尔回答了你的方法已经失效的原因。
恕我直言,适当的解决方案是使用 while 循环并自己进行循环增量。
Nick Bull answered on the reasons why your method broke already.
IMHO the appropriate solution would be to use a while loop and do the loop increments yourself.