Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString padding / space between characters

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

like image 495
Drew Avatar asked Jun 16 '12 03:06

Drew


2 Answers

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];
}];
like image 177
Ken Thomases Avatar answered Nov 14 '22 03:11

Ken Thomases


Try This :

NSString *string =[NSString stringWithString:@"1234"];
NSMutableArray *buffer = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
    [buffer addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
}
NSString *final_string = [buffer componentsJoinedByString:@" "];
like image 31
Hector Avatar answered Nov 14 '22 03:11

Hector