Detect if character is either a letter or a number

In objective-c, how would I check if a single character was a letter or a number? I would like to delete all other characters.

+5
source share
7 answers
NSCharacterSet *validChars = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *invalidChars = [validChars invertedSet];

NSString *targetString = [[NSString alloc] initWithString: @"..."];
NSArray *components = [targetString componentsSeparatedByCharactersInSet:invalidChars];

NSString *resultString = [components componentsJoinedByString:@""];
+6
source

To exclude 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]) { 
       ... 
    }
}
+8
source

, :

unichar ch = '5';

BOOL isLetter = [[NSCharacterSet letterCharacterSet] characterIsMember: ch];

BOOL isDigit  = [[NSCharacterSet decimalDigitCharacterSet] characterIsMember: ch];

NSLog(@"'%C' is a letter: %d or a digit %d", ch, isLetter, isDigit);
+5

C, ctype.h( Foundation). . .

char c = 'a';
if (isdigit(c)) {
    /* ... */
} else if (isalpha(c)) {
    /* ... */
}

/* or */
if (isalnum(c))
    /* ... */
+2

, ():


NSString* text = [...];
unichar character = [text characterAtIndex:0];

BOOL isNumber = (character >= '0' && character <= '9');

, ( , ..).

, , . ASCII-? ?

0

You can check them by comparing the ASCII value for the number (0-9 ASCII in the range 48 to 57). You can also use NSScanner in Objective-C to test for int or char.

0
source

All Articles