Sunday, May 19, 2013

NSString rangeOfCharacterFromSet example ios

[NSString rangeOfCharacterFromSet]

Finds and returns the range in the receiver of the first character from a given character set.
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
A character set. This value must not be nil.

Important: Raises an NSInvalidArgumentException if aSet is nil.
Return Value of [NSString rangeOfCharacterFromSet]
The range in the receiver of the first character found from aSet. Returns a range of{NSNotFound, 0} if none of the characters in aSet are found.
Discussion of [NSString rangeOfCharacterFromSet]
Invokes rangeOfCharacterFromSet:options: with no options.
This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.
Example of [NSString rangeOfCharacterFromSet]
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
    // newString consists only of the digits 0 through 9
Example of [NSString rangeOfCharacterFromSet]
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];

if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
  NSLog(@"This string contains illegal characters");
Example of [NSString rangeOfCharacterFromSet]
NSString *string = <your string>;

NSString *specialCharacterString = @"!~`@#$%^&*-+();:={}[],.<>?\\/\"\'";
NSCharacterSet *specialCharacterSet = [NSCharacterSet

if ([string.lowercaseString rangeOfCharacterFromSet:specialCharacterSet].length) {                
    NSLog(@"contains special characters");