Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if a character is either a letter or a number

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.

like image 670
user551353 Avatar asked Dec 13 '11 15:12

user551353


People also ask

How do you check if a character is a letter or number in C?

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.

How do you check if a character is a letter or number in Python?

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.

How do you check if a character is a letter or number in Javascript?

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.


1 Answers

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]) { 
       ... 
    }
}
like image 123
Jano Avatar answered Oct 04 '22 01:10

Jano