2012-06-16 14 views
6

Estoy buscando una manera fácil en Obj.C para hacer agregar un espacio entre cada carácter de mi cadena. Entonces "1234" aparecería como "1 2 3 4".NSString relleno/espacio entre caracteres

He encontrado un ejemplo de JavaScript perfecta aquí: https://stackoverflow.com/a/7437422/949538

¿alguien sabe de algo similar para Obj.C? Kerning es un PITA en iOS, y esto es todo lo que necesito de todos modos ...

¿Pensamientos/comentarios?

Gracias! - dibujó

+0

Incluso puede simplemente transcribir el javascript en Obj-C (¡esto es básico!). ¿Qué has intentado? – Vervious

Respuesta

4

intenta esto:

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

Parece que funciona. Solo un pensamiento; Creo que también podría poner esta línea - '[buffer addObject: [NSString stringWithFormat: @" "]' - en el ciclo for después de agregar el objeto de la cadena 'string'. – pasawaya

+0

@qegal ya podemos usar eso, pero 'buffer' es NSMutableArray, así que al final tenemos que usar' componentsJoinedByString' porque queremos obtener 'NSString' – Hector

+0

Fantástico. Funcionó perfectamente, gracias! – Drew

0

Haga esto:

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

Para hacer esto correctamente, teniendo en cuenta los problemas mencionados en el comentario de David Rönnqvist, hacer algo como esto:

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