2010-12-05 5 views

Répondre

12

Vous avez besoin d'une chaîne mutable, pas un NSString.

NSMutableString *str = [NSMutableString stringWithString:old_string]; 
[str insertString:@"-" atIndex:8]; 
[str insertString:@"-" atIndex:4]; 

Code fixe en fonction de la réponse de stko, qui est sans bug.

6

Vous devez d'abord veiller à insérer le tiret à l'index le plus haut. Si vous insérez d'abord à l'index 4, vous devrez insérer à l'index 9 au lieu de 8 pour le deuxième tiret.

par exemple. Cela ne produit pas la chaîne désirée ...

NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"]; 

[s insertString:@"-" atIndex:4]; // s is now @"abcd-efghij" 
[s insertString:@"-" atIndex:8]; // s is now @"abcd-efg-hij" 

Bien que celui-ci fait:

NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"]; 

[s insertString:@"-" atIndex:8]; // s is now @"abcdefgh-ij" 
[s insertString:@"-" atIndex:4]; // s is now @"abcd-efgh-ij" 
+0

Merci, je vais modifier ma réponse (car elle est toujours acceptée.) – Derrick

0

Voici une façon légèrement différente de le faire - ce qui est d'obtenir une copie mutable de votre NSString d'origine.

NSMutableString *newString = [originalString mutableCopy]; 

[newString insertString:@"-" atIndex:8]; 
[newString insertString:@"-" atIndex:4]; 

Puisque vous êtes sur l'iPhone - il est important de noter que depuis le newString est créé avec mutableCopy vous possédez la mémoire et sont responsables de le libérer à un moment futur.