Ios – NSString padding / space between characters

ioskerningnsstringobjective cpadding

I'm looking for an easy way in Obj.C to do add a space between each character of my string. So "1234" would come out looking like "1 2 3 4".

I've found a perfect javascript example here: https://stackoverflow.com/a/7437422/949538

Does anyone know of something similar for Obj.C? Kerning is a PITA in iOS, and this is ultimately all I need anyway…

Thoughts / comments?

Thanks!
– Drew

Best Answer

To do this correctly, taking into account the problems mentioned in David Rönnqvist's comment, do something like this:

NSMutableString* result = [origString mutableCopy];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
                           options:NSStringEnumerationByComposedCharacterSequences | NSStringEnumerationSubstringNotRequired
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
     if (substringRange.location > 0)
         [result insertString:@" " atIndex:substringRange.location];
}];