2010-11-15 9 views
2

Je sais que c'est la mauvaise façon de le faire (car il des erreurs), mais vous pouvez voir ce que je suis en train de faire:multiples cordes remplace en Objective C

NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@""]; 
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"&" withString:@""]; 
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"'" withString:@""]; 
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"-" withString:@""]; 
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"_" withString:@""]; 

J'ai un terme de recherche appelé " termes "et que vous souhaitez afficher une version nettoyée dans" urlTerm "??

Répondre

4

-stringByReplacingOccurrencesOfString: renvoie une nouvelle chaîne. La chaîne d'origine terms ne sera pas affectée par cette fonction. Même si terms sera affecté, la 2ème instruction ne réussira jamais car tous les espaces sont déjà + dans la première instruction et aucun double espace n'est laissé. (OK, il se trouve que "double espace" est un onglet: |.)

Vous pouvez utiliser

NSString* urlTerm = terms; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"\t" withString:@""]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"&" withString:@""]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"'" withString:@""]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"-" withString:@""]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"_" withString:@""]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
+0

Votre réponse avait un sens complet. Mais quand je le construis dans Xcode, il dit "Redéfinition de urlTerm" comme son erreur et la construction échoue ?? – benhowdle89

+0

@ benhowdle89: Avez-vous essayé la dernière mise à jour? – kennytm

+0

Était trop hâtive pour mettre votre code. Il fonctionne maintenant parfaitement maintenant que vous avez enlevé le NSString de chaque ligne merci – benhowdle89

1
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@""]; 

etc.

4
NSString *urlTerm = [terms stringByTrimmingCharactersInSet: 
[NSCharacterSet characterSetWithCharactersInString:@"\t&'-_"]]; 
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@"+"];