Objective-C Check for Unallowed Characters in String - objective-c

How would I, in objective-c, make it so only strings with a-z characters were allowed? I.E. no & characters, no - characters, etc.
Thanks!
Christian Stewart

NSCharacterSets are going to be the key here. First you'll need the character set of alphabetical characters:
NSCharacterSet* letters = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 26)];
And then, if you want to check if the string contains a character that's not a letter, you can use this set's inverse:
NSCharacterSet* notLetters = [letters invertedSet];
Then use NSString's rangeOfCharacterFromSet: with notLetters, and if the range doesn't start with NSNotFound, there are forbidden characters in your string.
NSRange badCharacterRange = [myString rangeOfCharacterFromSet:notLetters];
if (badCharacterRange.location != NSNotFound) // found bad characters

Related

How can I replace special characters by regex and Objective-C?

String: abc2_2fkf-lo
Now I want to use regex to delete the special characters as _ and -
The expect string as I want: abc22fkflo
Use stringByReplacingOccurrencesOfString.
NSString *string = #"abc2_2fkf-lo";
NSString *updated = [string stringByReplacingOccurrencesOfString:#"[-_]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
This replaces any occurrence of a - or _ character with the empty string.
Note that if you want to match a - character using [ ] in a regular expression, the - needs to be the first character to avoid its normal special use as a character range operator.

Check if all characters are uppercase in string - Obj C

I know I can check if a string contains uppercase letters but is there some built in function in Objective-C to check if all characters are uppercase letters? I want to avoid looping through each character to see if it contains a lowercase letter and then break out of the loop if it contains one as this takes up more memory and takes more time. Time is a constraint as I have to process thousands of strings.
An alternative approach that might appeal given your concerns: Use NSString's rangeOfCharactersFromSet: passing it NSCharacterSet's lowercaseLetterCharacterSet. If this finds anything then the string isn't all uppercase. It's a single line expression like the other current answers, but doesn't involve creating an uppercase copy of the string and works for all Unicode letters.
try this
NSString * myString;
[myString.uppercaseString isEqualToString:myString];
[your_string.uppercaseString isEqualToString:your_string];
If you need to process a lot of strings, especially long string may be following code will be faster
// In case you need process a lo of strings this set should be initialized before loop!
NSCharacterSet *set = [NSCharacterSet lowercaseLetterCharacterSet];
// check for allowed characters
BOOL isValid = ([string rangeOfCharacterFromSet:set].location == NSNotFound);
#implementation NSString (uppercaseOnly)
- (BOOL) allUpperCase {
return [self rangeOfCharacterFromSet:[[NSCharacterSet upperCaseLetterCharacterSet] invertedSet]].location == NSNotFound;
}

How to determine if the first character of a NSString is a letter

In my app
i need to know if the first character of a string is a letter or not
Im getting first character of the string like this
NSString *codeString;
NSString *firstLetter = [codeString substringFromIndex:1];
I can know it by comparing with a, b, c, .**.
if([firstLetter isEqualToString "a"] || ([firstLetter isEqualToString "A"] || ([firstLetter isEqualToString "b"] ......)
But is there any other method to know?
I need to display different colors for letters and symbols.
How can i achieve it in simple way?
First off, your line:
NSString *firstLetter = [codeString substringFromIndex:1];
does not get the first letter. This gives you a new string the contains all of the original string EXCEPT the first character. This is the opposite of what you want. You want:
NSString *firstLetter = [codeString substringToIndex:1];
But there is a better way to see if the first character is a letter or not.
unichar firstChar = [[codeString uppercaseString] characterAtIndex:0];
if (firstChar >= 'A' && firstChar <= 'Z') {
// The first character is a letter from A-Z or a-z
}
However, since iOS apps deal with international users, it is far from ideal to simply look for the character being in the letters A-Z. A better approach would be:
unichar firstChar = [codeString characterAtIndex:0];
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
if ([letters characterIsMember:firstChar]) {
// The first character is a letter in some alphabet
}
There are a few cases where this doesn't work as expected. unichar only holds 16-bit characters. But NSString values can actually have some 32-bit characters in them. Examples include many Emoji characters. So it's possible this code can give a false positive. Ideally you would want to do this:
NSRange first = [codeString rangeOfComposedCharacterSequenceAtIndex:0];
NSRange match = [codeString rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first];
if (match.location != NSNotFound) {
// codeString starts with a letter
}

How to omit a certain substring out of an NSString?

I would like to know how it is possible to omit a specific substring out an NSString, assuming the NSString does contain that substring.
For example:
Original string: "This is a string but these words should be omitted."
Substring to omit: "but these words should be omitted".
Result string: "This is a string."
Thanks ahead,
iLyrical.
NSString *originalString = #"This is a string but these words should be omitted.";
NSString *substringToOmit = #" but these words should be omitted";
NSString *resultString = [originalString stringByReplacingOccurencesOfString:substringToOmit
withString:#""];
See NSString's stringByReplacingOccurrencesOfString:withString:. You may also want to trim the trailing whitespace with stringByTrimmingCharactersInSet:.

searching and replacing an extended ASCII in a string

a noob question here.
I am trying to make an automatic search and replace process for characters' ASCII values in a string.
so, I have a string constructed from a content of a UITextField
NSString *searchText;
searchText = (mmText.text);
then I do a little loop and check all entered characters for their ASCII values. if they're not in the allowed range I want to search and replace them with something else (? for now)
so let's say I am in the loop and I get to a ASCII 45 character (it's a minus sign):
int asciiCode = 45;
now I would like to find the ASCII 45 character in the string and replace it with a question mark
This is what I am doing at the moment:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
NSRange matchSpace;
matchSpace = [searchText rangeOfString: ascStr];
if (matchSpace.location == NSNotFound)
{}
else
NSMutableString *searchandReplace = [NSMutableString stringWithString: searchText];
[searchandReplace replaceCharactersInRange: [searchandReplace rangeOfString: ascStr] withString: #"?"];
mmText.text = searchandReplace;
}
This works fine for a regular ASCII value (0-255), but it doesn't seem to work for the extended ASCII values coming from foreign languages. For example when using the Korean language mode, one of the main character looks like a double crossed W, but when printed via NSLog it looks like a copyright sign. This is probably the reason the search and replace procedure doesn't work for it. It has an ASCII value of 8361.
any ideas ? thank you!
it turns out it was as simple as changing:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
to
NSString *ascStr = [NSString stringWithFormat:#"%C", asciiCode];
%c
8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit
%C
16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit