Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check NSString for special characters

I want to check an NSString for special characters, i.e. anything except a-z, A-Z and 0-9.

I don't need to check how many special characters are present, or their positions, I just need to know whether a particular string contains any or not. If it does, then I want to be able to display "Error!", or something similar.

For example, jHfd9982 is OK but asdJh992@ is not.

Also, letters with accents, diacritics, etc. should not be allowed.

How would I go about this?

Thanks!

Michael

like image 857
Michael Avatar asked Feb 19 '10 14:02

Michael


People also ask

Is NSString UTF 8?

An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .

What is NSString in objective c?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What is NSString in swift?

NSString : Creates objects that resides in heap and always passed by reference. String: Its a value type whenever we pass it , its passed by value. like Struct and Enum, String itself a Struct in Swift.


3 Answers

NSCharacterSet * set = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
  NSLog(@"This string contains illegal characters");
}

You could also use a regex (this syntax is from RegexKitLite: http://regexkit.sourceforge.net ):

if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
  NSLog(@"This string contains illegal characters");
}
like image 86
Dave DeLong Avatar answered Oct 15 '22 03:10

Dave DeLong


Here the code you can use it to check the string has any special character or not

NSString *string = <your string>;

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

if ([string.lowercaseString rangeOfCharacterFromSet:specialCharacterSet].length) {                
    NSLog(@"contains special characters");
}
like image 10
loganathan Avatar answered Oct 15 '22 03:10

loganathan


You want to search NSString using a character set if it cant find any characters in the string then rangeOfCharacterFromSet: will return a range of {NSNotFound, 0}

The character set would be like [NSCharacterSet symbolCharacterSet] or your own set. Note you can also invert character sets so you could have a set of acceptable characters

like image 6
mmmmmm Avatar answered Oct 15 '22 04:10

mmmmmm