NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] 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");
}
Returns a Boolean value that indicates whether the receiver has at least one member in a given character plane.
- (BOOL)hasMemberInPlane:(uint8_t)thePlane
Parameters of [NSCharacterSet hasMemberInPlane]
thePlane
A character plane.
Return Value
YES if the receiver has at least one member in thePlane, otherwise NO.
Discussion of [NSCharacterSet hasMemberInPlane]
This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane is plane 0.
NSCharacterSet hasMemberInPlane example.
NSCharacterSet *charset = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableArray *array = [NSMutableArray array];
for (int plane = 0; plane <= 16; plane++) {
if ([charset hasMemberInPlane:plane]) {
UTF32Char c;
for (c = plane << 16; c < (plane+1) << 16; c++) {
if ([charset longCharacterIsMember:c]) {
UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe
NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding];
[array addObject:s];
}
}
}
}
Returns a Boolean value that indicates whether a given character is in the receiver.
- (BOOL)characterIsMember:(unichar)aCharacter
Parameters
aCharacter
The character to test for membership of the receiver.
Return Value of [NSCharacterSet characterIsMember]
YES if aCharacter is in the receiving character set, otherwise NO.
NSCharacterSet characterIsMember example.
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]) {
...
}
}
Example of [NSCharacterSet characterIsMember].
To see if your 'substring' variable in one of your sets you would do:
if ([substring rangeOfCharacterFromSet:setOne].location != NSNotFound) {
// substring is in setOne
} else if ([substring rangeOfCharacterFromSet:setTwo].location != NSNotFound) {
// substring is in setTwo
}
Another option is to work with characters.
for (int i = 0; i<[word length]; i++) {
unichar ch = [word characterAtIndex:i];
if ([setOne characterIsMember:ch]) {
// in setOne
} else if ([setTwo characterIsMember:ch]) {
// in setTwo
}
}
NSCharacterSet characterIsMember example.
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered
{
for (int i = 0; i < [textEntered length]; i++)
{
unichar c = [textEntered characterAtIndex:i];
if ([disallowedCharacters characterIsMember:c])
{
return NO;
}
}
return YES;
}
Returns an NSData object encoding the receiver in binary format.
- (NSData *)bitmapRepresentation
Return Value
An NSData object encoding the receiver in binary format.
Discussion of [NSCharacterSet bitmapRepresentation]
This format is suitable for saving to a file or otherwise transmitting or archiving.
A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To test for the presence of a character with decimal Unicode value n in a raw bitmap representation, use an expression such as the following:
unsigned char bitmapRep[8192];
if (bitmapRep[n >> 3] & (((unsigned int)1) << (n & 7))) {
/* Character is present. */
}
Example of [NSCharacterSet whitespaceCharacterSet].
There is method for that in NSString class. Check stringByTrimmingCharactersInSet:(NSCharacterSet *)set. You should use [NSCharacterSet whitespaceCharacterSet] as parameter:
Returns a character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
+ (id)whitespaceAndNewlineCharacterSet
Return Value of [NSCharacterSet whitespaceAndNewlineCharacterSet]
A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
Example of [NSCharacterSet whitespaceAndNewlineCharacterSet].
str = [aSearchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
str = [str retain]; // Keep object alive beyond the scope of this method
Of course if you keep an object alive like this, you must release it yourself somewhere in your code. So if you want this variable to be overridden each time the method is called, use
[str release];
str = [aSearchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
str = [str retain]; // Keep object alive beyond the scope of this method
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)
Returns a character set containing the characters in the categories of Uppercase Letters and Titlecase Letters.
+ (id)uppercaseLetterCharacterSet
Return Value
A character set containing the characters in the categories of Uppercase Letters and Titlecase Letters.
Discussion of [NSCharacterSet uppercaseLetterCharacterSet]
Informally, this set is the set of all characters used as uppercase letters in alphabets that make case distinctions.
NSString *s = @"This is a string";
int count=0;
for (i = 0; i < [s length]; i++) {
BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:i]];
if (isUppercase == YES)
count++;
}
Example of [NSCharacterSet uppercaseLetterCharacterSet].
Returns a character set containing the characters in the category of Symbols.
+ (id)symbolCharacterSet
Return Value
A character set containing the characters in the category of Symbols.
Discussion of [NSCharacterSet symbolCharacterSet]
These characters include, for example, the dollar sign ($) and the plus (+) sign.
NSCharacterSet symbolCharacterSet example.
NSCharacterSet* symbols = [NSCharacterSet symbolCharacterSet];
if([symbols characterIsMember: yourCharacter]) {
//Check Your condition here
}
If you want to include many characters Use a combined NSCharacterset with NSMutableCharacterSet..
NSMutableCharacterSet *space = [NSMutableCharacterSet characterSetWithCharactersInString:@" "];
[space formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
Use the space characterset to check the character
Example of [NSCharacterSet symbolCharacterSet].
test if for invalid chars:
[NSCharacterSet symbolCharacterSet]
rangeOfCharacterFromSet == YES if the array contains a char from the set
to rm them all:
id s = @"$bla++$bleb+$blub-$b";
NSCharacterSet *ch = [NSCharacterSet symbolCharacterSet]
s = [[s componentsSeparatedByCharactersInSet:ch] componentsJoinedByString:@""];
NSLog(@"%@ - %@",ch, s);
NSCharacterSet symbolCharacterSet example.
while ([s scanCharactersFromSet:[NSCharacterSet symbolCharacterSet] intoString:&read]) { //symbolCharacterSet
for(int idx=0;idx<read.length;idx=idx+6) //For Some Reason "6" works with + sign and Emojis...
{
NSString *word=[read substringFromIndex:0]; //substringWithRange:NSMakeRange(idx, 2)]; <-- I switched out the range and decided to get the WHOLE string.
CGSize s = [word sizeWithFont:self.font];
if(drawPoint.x + s.width > rect.size.width) {
drawPoint = CGPointMake(0, drawPoint.y + s.height);
Returns a character set containing the characters in the category of Punctuation.
+ (id)punctuationCharacterSet
Return Value
A character set containing the characters in the category of Punctuation.
Discussion of [NSCharacterSet punctuationCharacterSet]
Informally, this set is the set of all non-whitespace characters used to separate linguistic units in scripts, such as periods, dashes, parentheses, and so on.
NSCharacterSet punctuationCharacterSet example.
If you already know the characters that you want to remove.
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+-(),. "];
NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet];
NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
If you don't know the characters, you can use the different character sets available already
Example of [NSCharacterSet punctuationCharacterSet].
To check if a string has any characters belonging to a set, you simply do this:
NSString *testString = @"hello$%^";
NSRange r = [testString rangeOfCharactersFromSet:[NSCharacterSet punctuationCharacterSet]];
if (r.location != NSNotFound) {
// the string contains a punctuation character
}
If you want to know all of the locations of the punctuation characters, just keep searching with a different input range. Something like:
NSRange searchRange = NSMakeRange(0, [testString length]);
while (searchRange.location != NSNotFound) {
NSRange foundRange = [searchString rangeOrCharacterFromSet:[NSCharacterSet punctuationCharacterSet] options:0 range:searchRange];
searchRange.location = foundRange.location + 1;
searchRange.length = [testString length] - searchRange.location;
if (foundRange.location != NSNotFound) {
// found a character at foundRange.location
}
}
// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
[data replaceObjectAtIndex: i
withObject: [[data objectAtIndex: i] componentsSeparatedByString: @","]];
}
NSCharacterSet newlineCharacterSet example.
NSString *address = @"129 City Road \nShoreditch \nLondon EC1V 1JB";
address = [address stringByReplacingOccurrencesOfString:@"\n" withString:@""];
address = [address stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
This worked and i got the output like :
Returns a character set containing the characters in the category of Lowercase Letters.
+ (id)lowercaseLetterCharacterSet
Return Value
A character set containing the characters in the category of Lowercase Letters.
Discussion of [NSCharacterSet lowercaseLetterCharacterSet]
Informally, this set is the set of all characters used as lowercase letters in alphabets that make case distinctions.
if ([myString rangeOfCharacterFromSet:lowerCaseSet].location == NSNotFound)
NSLog(@"String is in upper case.");
else
NSLog(@"String has invalid characters.");
Example of [NSCharacterSet lowercaseLetterCharacterSet].
// Check if the added string contains lowercase characters.
// If so, those characters are replaced by uppercase characters.
// But this has the effect of losing the editing point
// (only when trying to edit with lowercase characters),
// because the text of the UITextField is modified.
// That is why we only replace the text when this is really needed.
NSRange lowercaseCharRange;
lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];
Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
+ (id)illegalCharacterSet
Return Value of [NSCharacterSet illegalCharacterSet]
A character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
// Make sure you are the text fields 'delegate', then this will get called before text gets changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// This will be the character set of characters I do not want in my text field. Then if the replacement string contains any of the characters, return NO so that the text does not change.
NSCharacterSet *unacceptedInput = nil;
// I have 4 types of textFields in my view, each one needs to deny a specific set of characters:
if (textField == emailField) {
// Validating an email address doesnt work 100% yet, but I am working on it.... The rest work great!
if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
} else {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
}
} else if (textField == phoneField) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
} else if (textField == fNameField || textField == lNameField) {
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
} else {
unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
}
// If there are any characters that I do not want in the text field, return NO.
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
Returns a character set containing all individual Unicode characters that can also be represented as composed character sequences.
+ (id)decomposableCharacterSet
Return Value of [NSCharacterSet decomposableCharacterSet]
A character set containing all individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of “standard decomposition” in version 3.2 of the Unicode character encoding standard.
Discussion of [NSCharacterSet decomposableCharacterSet]
These characters include compatibility characters as well as pre-composed characters.
Note: This character set doesn’t currently include the Hangul characters defined in version 2.0 of the Unicode standard.
NSCharacterSet decomposableCharacterSet example.
NSString *inputString = @"Västerås ;; Swed en ";
NSLog(@"Input String %@",inputString);
inputString = [inputString lowercaseString]; // Lower case
Returns a character set containing the characters in the category of Decimal Numbers.
+ (id)decimalDigitCharacterSet
Return Value
A character set containing the characters in the category of Decimal Numbers.
Discussion of [NSCharacterSet decimalDigitCharacterSet]
Informally, this set is the set of all characters used to represent the decimal values 0 through 9. These characters include, for example, the decimal digits of the Indic scripts and Arabic.
Example of [NSCharacterSet decimalDigitCharacterSet].
Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// newString consists only of the digits 0 through 9
}
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:
Parameters
aString
A string containing characters for the new character set.
Return Value of [NSCharacterSet characterSetWithCharactersInString]
A character set containing the characters in aString. Returns an empty character set if aString is empty.
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
Once you have that, you invert it to everything that's not in your original string:
s = [s invertedSet];
And you can then use a string method to find if your string contains anything in the inverted set:
NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
NSLog(@"the string contains illegal characters");
}
Example of [NSCharacterSet characterSetWithCharactersInString].
NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
unichar character = [yourString characterAtIndex:i];
if ([characters characterIsMember:character]) characterCount++;
}
NSCharacterSet* theCaps [NSCharacterSet capitalizedLetterCharacterSet];
if ([theCaps characterIsMember: aChar])
{
//Character is an upper case character
}
else
{
//Character is not an upper case character.
}
Example of [NSCharacterSet capitalizedLetterCharacterSet].
Returns a character set containing the characters in the categories Letters, Marks, and Numbers.
+ (id)alphanumericCharacterSet
Return Value
A character set containing the characters in the categories Letters, Marks, and Numbers.
Discussion of [NSCharacterSet alphanumericCharacterSet]
Informally, this set is the set of all characters used as basic units of alphabets, syllabaries, ideographs, and digits.
Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.
First, I get all the EntityC that satisfy the condition EntityC.name equal to 'SomeName'
NSPredicate *p = [NSPredicate predicateWithFormat:@"name like %@", @"SomeName];
...
NSArray *res = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
Then I get an array of EntityB from above query
NSArray *parentBs = [res valueForKeyPath:@"@distinctUnionOfObjects.parent"];
Than get array of EntityB that satisfy the condition EntityB.EntitiesC.name equal to 'SomeName':
Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.
Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.
Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.