2008-11-02 8 views

Répondre

85

utilisation -[NSString rangeOfString:]:

- (NSRange)rangeOfString:(NSString *)aString; 

Trouve et renvoie la plage de la première occurrence d'une chaîne donnée dans le récepteur. J'ai écrit une catégorie pour étendre l'objet NSString original.

+8

Et 'NSRange. location' est l'index réel. – devios1

+1

'if (NSRange.location! = NSNotFound)' alors vous avez trouvé une correspondance. –

18

Peut-être que vous pouvez le référencer. (Vous pouvez également voir le article dans mon blog aussi.)

ExtendNSString.h:

#import <Foundation/Foundation.h> 

@interface NSString (util) 

- (int) indexOf:(NSString *)text; 

@end 

ExtendNSStriing.m:

#import "ExtendNSString.h" 

@implementation NSString (util) 

- (int) indexOf:(NSString *)text { 
    NSRange range = [self rangeOfString:text]; 
    if (range.length > 0) { 
     return range.location; 
    } else { 
     return -1; 
    } 
} 

@end 
+3

Une meilleure utilisation de NSRange doit être comme suit 'code' - (int) indexOf: (NSString *) text { NSRange plage = [self rangeOfString: text]; if (range.location! = NSNotFound) { return range.location; } else { return -1; } } 'code' – loretoparisi

+0

Solution agréable, propre et réutilisable. Et j'ai voté -1 à Apple pour nous avoir obligé à écrire des fonctions d'assistance si manifestement simples en 2014. Pourquoi ne peuvent-ils pas nous rendre la vie plus facile? –

28

Si vous voulez savoir au moment où une chaîne contient la chaîne b utilise mon chemin pour le faire.

#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound) 

//using 
NSString a = @"PUC MINAS - BRAZIL"; 

NSString b = @"BRAZIL"; 

if(contains(a,b)){ 
    //TO DO HERE 
} 

Ceci est moins lisible, mais améliore les performances

+1

Juste ce dont j'avais besoin --- Merci! –

+0

vraiment génial! –