RGriffiths
RGriffiths

Reputation: 5970

Identifying if there are unwanted characters in a string

I have the a series of UITextFields that enable the user to enter text. I need to check the text for characters that are not allowed. I can have a series of lines such as:

noOfBadChars = [[textBox1.text componentsSeparatedByString:@"&"] count];
noOfBadChars = noOfBadChars + [[textBox2.text componentsSeparatedByString:@"*"] count];
if (noOfBadChars>1)
{
    ….
}

but is there a simple way of checking this as I don't want to have to check for every bad char separately, or perhaps there is a way of limiting the entry to just A to Z chars?

Upvotes: 0

Views: 77

Answers (2)

Duncan C
Duncan C

Reputation: 131398

componentsSeparatedBy methods will potentially create a whole bunch of objects as a side-effect. If you don't need the substrings, it would be much more efficient to use a method like

rangeOfCharacterFromSet:options:range.

You could write a loop that would step through the string, finding each character from the set of unwanted characters.

Upvotes: 0

nhgrif
nhgrif

Reputation: 62052

NSCharacterSet *charsToRemove = [NSCharacterSet
    characterSetWithCharactersInString:@"example"];

Where example is replace with the characters you want to remove.

NSString *finalString = [[originalString 
    componentsSeperatedByCharactersInCharacterSet: charsToRemove]
    componentsJoinedByString: @""];

This will replace the entered text with a text that has all the characters removed.

Otherwise, if you just want to check and see whether it contained a bad character, you can do:

NSArray *temp = [originalString componentsSeperatedByCharactersInCharacterSet:
    charsToRemove];
if ([temp count] > 1) {
    // do stuff
}

NSCharacterSet has a lot of constant character sets for common needs.

NSCharacterSet *charsToKeep = [NSCharacterSet letterCharacterSet];

That will make charsToKeep a character set including only letters. Now you can use invertedSet to get the inverse.

NSCharacterSet *charsToRemove = [charsToKeep 
    invertedSet];

charsToRemove will now be a character set that includes every character that's not in the letterCharacterSet.

You can do this all in one line as such:

NSCharacterSet *charsToRemove = [[NSCharacterSet letterCharacterSet] 
    invertedSet];

If you want letters AND numbers, use alphanumericCharacterSet instead of letterCharacterSet.

The official documentation has a list of all the character sets.

Upvotes: 1

Related Questions