在IPhone中格式化字符串

在IPhone中格式化字符串,iphone,nsstring,Iphone,Nsstring,我需要在字符串中每4个字符后添加空格。。例如,如果字符串是aaaaaa,我需要将其格式化为aaaaaa。我尝试了以下代码,但它对我无效 NSMutableString *currentFormattedString = [[NSMutableString alloc] initWithString:formattedString]; int count = [formattedString length]; for (int i = 0; i<count; i++) {

我需要在字符串中每4个字符后添加空格。。例如,如果字符串是
aaaaaa
,我需要将其格式化为
aaaaaa
。我尝试了以下代码,但它对我无效

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];

        }

    }
NSMutableString*currentFormattedString=[[NSMutableString alloc]initWithString:formattedString];
int count=[formattedString长度];

对于(inti=0;i我找到了以下将字符串格式化为电话号码格式的方法,但是看起来您可以轻松地将其更改为支持其他格式

NSString*text=[[NSString alloc]initWithString:@“aaaaaa”];
NSString*result=[[NSString alloc]init];
双重计数=text.length/4;
如果(计数>1){

对于(int i=0;i你没有说什么代码不起作用,所以很难确切地知道该回答什么。作为一个提示-在未来的问题中,不要只说“它不起作用”,而是说明什么不起作用以及它是如何起作用的。然而

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];

    }

}
NSMutableString*currentFormattedString=[[NSMutableString alloc]initWithString:formattedString];
int count=[formattedString长度];

对于(int i=0;iNick Bull回答了您的方法已经失败的原因。
我认为合适的解决方案是使用while循环,然后自己执行循环增量

NSInteger i = 4; // first @" " should be inserted after the 4th (index = 3) char
while (i < count) {
    [currentFormattedString insertString:@" " atIndex:i];
    count ++; // you did insert @" " so the length of the string increased
    i += 5; // you now must skip 5 (" 1234") characters
}
NSInteger i=4;//应在第四个(索引=3)字符后插入第一个@“”
而(我<计数){
[currentFormattedString insertString:@“atIndex:i];
count++;//您确实插入了@“”,因此字符串的长度增加了
i+=5;//现在必须跳过5个(“1234”)字符
}

首先找到字符串的长度。将字符串放入for循环,并设置一个条件,即每4个字符后应该有一个空格。很简单。请记住,只有当原始字符串长度是4的倍数时,这才有效。
NSInteger i = 4; // first @" " should be inserted after the 4th (index = 3) char
while (i < count) {
    [currentFormattedString insertString:@" " atIndex:i];
    count ++; // you did insert @" " so the length of the string increased
    i += 5; // you now must skip 5 (" 1234") characters
}