In objective-c, how would I check if a single character was either a letter or a number? I would like to eliminate all other characters.
The isalpha() function checks whether a character is an alphabet or not. In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0.
Python has a built-in Isalpha() function which returns true if the character is a letter otherwise returns false. Using for loop, traverse over the string and apply isalpha function on all the characters. This function will identify all numeric or special characters in a string.
To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned.
To eliminate non letters:
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notLetters = [[NSCharacterSet characterSetWithCharactersInString:letters] invertedSet];
NSString *newString = [[string componentsSeparatedByCharactersInSet:notLetters] componentsJoinedByString:@""];
To check one character at a time:
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if ([notLetters characterIsMember:c]) {
...
}
}
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