Domanda

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

È stato utile?

Soluzione

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:@" "];

Altri suggerimenti

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

Do this:

    NSString *string =[NSString stringWithString:@"1234"];

    NSMutableString *spacedString= [NSMutableString stringWithString:[NSString stringWithFormat:@"%C",[string characterAtIndex:0]]];

    for(int i = 1; i<[string length];i++)
    {
        [spacedString appendString:[NSString stringWithFormat:@" %C",[string characterAtIndex:i]]];
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top