0

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

4 Answers 4

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

@linuxios i hav to answer like this?
No, you don't. I just wanted to get it off the low quality list (where it didn't necessarily belong), and just clean up the code formatting a little. Nothing wrong with the way you did it, just try to indent code correctly next time.
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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.