2010-11-10 10 views
1

Salut Comment puis-je remplacer NSString tableau d'utilisation à un autre tableau comme celui-ciComment remplacer NSString utiliser le tableau à un autre tableau

@"Hello world" 

{a, b, c, d, e, ...} - > {1,2,3,4,5, ..} = @ "H5llo worl4"

et puis-je remplacer sans tableau ?? totalement je veux remplacer 10 caractères d'une chaîne à 10 autres caractères. Comment puis-je faire cela?

Répondre

1

boucle dans le tableau et remplacer chaque personnage à son tour:

// Get the two arrays of characters to replace and their replacements 
NSArray *fromArray = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", nil]; 
NSArray *toArray = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil]; 

// Make a mutable version of our string 
NSMutableString *newString = [NSMutableString stringWithString:@"Hello World"]; 

// Deal with each replacement in turn 
for (uint n = 0; n < [fromArray count]; ++n) 
    [newString replaceOccurrencesOfString:[fromArray objectAtIndex:n] withString:[toArray objectAtIndex:n] options:NSLiteralSearch range:NSMakeRange(0, [newString length])]; 

// Output the new string 
NSLog(@"%@", newString); 

Ce code n'est pas grand bien - si les deux tableaux sont différentes longueurs?

+0

Merci non, ils avoir la même longueur. – mamrezo

+0

@mamrezo vous feriez mieux d'examiner l'efficacité ici et peut-être l'exactitude si vous pouvez avoir des substitutions qui se chevauchent – rano

0

Vous pouvez utiliser un NSDictionary pour stocker votre tableau associatif (qui contient la chaîne de remplacement et sa clé).

boucle Ensuite, vous pouvez à travers vos éléments dans le NSDictionary en utilisant un fast enumeration afin que vous puissiez pourraient le remplacer en utilisant stringByReplacingOccurrencesOfString:withString:options:range:.

Cette méthode est mieux que d'appeler replaceOccurrencesOfString:withString: car en spécifiant la plage, vous pouvez éviter de re-boucle sur une chaîne déjà subsituted et vous éviterez ainsi l'application des substitutions enchaînées (ie. a->i, i->4)

Questions connexes