jannath
jannath

Reputation: 5

how to add comma to string after every nth character in xcode

my problem is pretty simple. I assign a value to string variable in xcode which looks like this:

ARAMAUBEBABRBGCNDKDEEEFO and I need it like this:

AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO The length is different in each variable.

thanx in advance

Upvotes: 0

Views: 1890

Answers (4)

user2387149
user2387149

Reputation: 1218

This function is usefull for numbers that need coma every thousands... which is what I wanted, hope it helps.

//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;
}

Upvotes: 4

justin
justin

Reputation: 104698

This would work well when your string is not very large:

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

If the string is very large, you should favor to compose it without insertion (append-only).

(define your own error detection)

Upvotes: 0

Bala
Bala

Reputation: 136

Try this:

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

Upvotes: 1

Bryan Chen
Bryan Chen

Reputation: 46578

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

Upvotes: 1

Related Questions