iosobjective-cxcodensstringnsmutablestring

NSString append WhiteSpace for every 4 Character


I have a string like @"1234123412341234", i need to append space between every 4 chars like.

@"1234 1234 1234 1234"

i.e, I need a NSString like Visa Card Type. I have tried like this but i didn't get my result.

-(void)resetCardNumberAsVisa:(NSString*)aNumber
{
  NSMutableString *s = [aNumber mutableCopy];

  for(int p=0; p<[s length]; p++)
  {
    if(p%4==0)
    {
        [s insertString:@" " atIndex:p];
    }
  }
  NSLog(@"%@",s);
}

Solution

  • You should do like this:

    - (NSString *)resetCardNumberAsVisa:(NSString*)originalString {
        NSMutableString *resultString = [NSMutableString string];
    
        for(int i = 0; i<[originalString length]/4; i++)
        {
            NSUInteger fromIndex = i * 4;
            NSUInteger len = [originalString length] - fromIndex;
            if (len > 4) {
                len = 4;
            }
    
            [resultString appendFormat:@"%@ ",[originalString substringWithRange:NSMakeRange(fromIndex, len)]];
        }
        return resultString;
    }
    

    UPDATE:

    You code will be right on the first inserting space charactor:

    This is your originalString:

    Text:     123412341234
    Location: 012345678901
    

    Base on your code, on the first you insert space character, you will insert at "1" (with location is 4)

    And after that, your string is:

    Text:     1234 12341234
    Location: 0123456789012
    

    So, you see it, now you have to insert second space charater at location is 9 (9%4 != 0)

    Hope you can fix your code by yourself!