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:
I have been searching this for hours... Can someone please answer this question???
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)
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) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With