Friday, June 14, 2013

NSCharacterSet characterSetWithRange example in Objective C (iOS).


NSCharacterSet characterSetWithRange

Returns a character set containing characters with Unicode values in a given range.

+ (id)characterSetWithRange:(NSRange)aRange

Parameters
aRange
A range of Unicode values.
aRange.location is the value of the first character to return; aRange.location + aRange.length– 1 is the value of the last.

Return Value
A character set containing characters whose Unicode values are given by aRange. If aRange.length is 0, returns an empty character set.

Discussion of [NSCharacterSet characterSetWithRange]
This code excerpt creates a character set object containing the lowercase English alphabetic characters:

NSCharacterSet characterSetWithRange example.
NSRange lcEnglishRange;
NSCharacterSet *lcEnglishLetters;

lcEnglishRange.location = (unsigned int)'a';
lcEnglishRange.length = 26;
lcEnglishLetters = [NSCharacterSet characterSetWithRange:lcEnglishRange];

Example of [NSCharacterSet characterSetWithRange].
You can make your character sets as follows for arbitrary ranges of ASCII characters:

NSCharacterSet *a_to_d_Set = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 'd'-'a' + 1)];
NSCharacterSet *e_to_l_Set = [NSCharacterSet characterSetWithRange:NSMakeRange('e', 'l'-'e' + 1)];
Of course, you could equivalently write:

NSCharacterSet *a_to_d_Set = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 4)];

NSCharacterSet characterSetWithRange example.
This method is Unicode-aware. If by "Upper case charecter" you just mean A-Z, use

NSCharacterSet* uppercaseCharSet =
    [NSCharacterSet characterSetWithRange:NSMakeRange('A', 26)];

End of NSCharacterSet characterSetWithRange example article.