如何在xcode中的每个第n个字符后添加逗号到字符串

时间:2012-08-31 09:26:02

标签: iphone nsstring xcode4.3

我的问题非常简单。我为xcode中的字符串变量赋值,如下所示:

ARAMAUBEBABRBGCNDKDEEEFO 我需要这样:

AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO 每个变量的长度都不同。

提前

thanx

4 个答案:

答案 0 :(得分:4)

这个函数对于每千个需要逗号的数字很有用......这就是我想要的,希望它有所帮助。

//add comas to a a string... 
//example1: @"5123" = @"5,123" 
//example2: @"123" = @"123" 
//example3: @"123123123" = @"123,123,123"
-(NSString*) addComasToStringEvery3chrsFromRightToLeft:(NSString*) myString{
    NSMutableString *stringFormatted = [NSMutableString stringWithFormat:@"%@",myString];
        for(NSInteger i=[stringFormatted length]-3;i>0;i=i-3) {
            if (i>0) {
                [stringFormatted insertString: @"," atIndex: i];
            }
        }
    return stringFormatted;
}

答案 1 :(得分:1)

NSString *yourString; // the string you want to process
int len = 2;  // the length
NSMutableString *str = [NSMutableString string];
int i = 0;
for (; i < [yourString length]; i+=len) {
    NSRange range = NSMakeRange(i, len);
    [str appendString:[yourString substringWithRange:range]];
    [str appendString:@","];
}
if (i < [str length]-1) {  // add remain part
    [str appendString:[yourString substringFromIndex:i]];
}
// str now is what your want

答案 2 :(得分:1)

试试这个:

int num;
NSMutableString *string1 = [NSMutableString stringWithString: @"1234567890"];   
num = [string1 length];
for(int i=3;i<=num+1;i++) {
  [string1 insertString: @"," atIndex: i];
  i+=3;
}

答案 3 :(得分:0)

当你的字符串不是很大时,这会很好用:

NSString * StringByInsertingStringEveryNCharacters(NSString * const pString,
                                                   NSString * const pStringToInsert,
                                                   const size_t n) {
    NSMutableString * const s = pString.mutableCopy;
    for (NSUInteger pos = n, advance = n + pStringToInsert.length; pos < s.length; pos += advance) {
        [s insertString:pStringToInsert atIndex:pos];
    }
    return s.copy;
}

如果字符串非常大,你应该倾向于在没有插入的情况下编写它(仅追加)。

(定义您自己的错误检测)