2010-08-19 5 views
12

Je souhaite poser une question à propos de l'objectif C. NSString * contient-il certaines fonctions pour vérifier que NSString * contient une chaîne dans le fichier UITextField.text? Par exempleComment vérifier le NSString contient le '%' ou pas?

NSString *checkString = @"abcd%" 

if(checkString contains '%') // I want this function 
    return YES; 
else 
    return NO; 
+0

UITextField contient toujours un string. – jtbandes

+0

@jtbandes, merci pour votre réponse. J'ai changé la question en fonction des commentaires. S'il vous plaît, jetez un oeil. – Questions

Répondre

7

Vous pouvez utiliser - (NSRange)rangeOfString:(NSString *)aString. Le code ressemblera à quelque chose comme:

NSRange range = [UITextField.text rangeOfString:@"!"]; 

if (range.length > 0){ 
    NSLog(@"String contains '!'"); 
} 
else { 
    NSLog(@"No '!' found in string"); 
} 
+2

range.length est NSUinteger. c'est toujours> = 0 [link] (https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/doc/uid/ 20000018-SW23) – jackal

+0

Merci, c'est vrai. J'ai modifié mon commentaire. Ça devrait être> 0. –

44
if([checkString rangeOfString:@"%"].location != NSNotFound) 
    // hooray! 
+0

Sur une ligne, comme on les aime! –

+3

'if ([checkString rangeOfString: @"% "]. Length) // encore plus concis' – wxactly

2

Le code du post précédent n'est pas correct

NSRange range = [UITextField.text rangeOfString:@"!"]; 

if (range.length >= 0){ 
    NSLog(@"String contains '!'"); 
} 
else { 
    NSLog(@"No '!' found in string"); 
} 

Il devrait être "range.length> 0"

Questions connexes