Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test If An NSString Contains a Letter

Tags:

iphone

I'm working on an iPhone project and I need to check if the user's input in a UITextfield contains a letter. More generally if an NSString contains a letter.

I tried this with a giant if loop with the rangeofstring:@"A".location == NSNotFound and then did OR rangeofstring:@"B".location == NSNotFound

and so on....

But:

  1. It doesn't seem to work
  2. There has to be a simple line of code to check if the NSString contains letters.

I have been searching this for hours... Can someone please answer this question???

like image 952
Jude Michael Murphy Avatar asked Dec 01 '22 01:12

Jude Michael Murphy


2 Answers

Use an NSCharacterSet. Note that letterCharacterSet includes all things that are "letters" or "ideographs." So that includes é and 中, but usually that's what you want. If you want a specific set of letters (like English letters), you can construct your own NSCharacterSet with them using characterSetWithCharactersInString:.

if ([string rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location == NSNotFound)
like image 129
Rob Napier Avatar answered Dec 03 '22 14:12

Rob Napier


If you want to make sure the text has a certain letter in it (as opposed to just ANY letter), use the rangeOfString: message. For example, to ensure the text contains the letter "Q":

NSString *string = @"poQduu";


if  ([string rangeOfString:@"Q"].location != NSNotFound) {
    DLog (@"Yes, we have a Q at location %i", [string rangeOfString:@"Q"].location );
}

As others (Rob Napier) note, if you want to find ANY letter, use the rangeOfCharacterFromSet: message.

if ([string rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound) ...
like image 22
Mike Fahy Avatar answered Dec 03 '22 13:12

Mike Fahy