How can I count the number of non-alphanumeric characters in an NSString object?
I'm diving into iOS development and I'm still getting familiar with the NSString object. I'm at a point where I need to count the number of non-alphanumeric characters in a 开发者_开发知识库string. One approach I came up with was stripping the non-alphanumeric characters from the string, then subtracting the length of the stripped string from the length of the original string, like so...
NSCharacterSet *nonalphanumericchars = [[NSCharacterSet alphanumericCharacterSet ] invertedSet];
NSString *trimmedString = [originalString stringByTrimmingCharactersInSet:nonalphanumericchars];
NSInteger numberOfNonAlphanumericChars = [originalString length] - [trimmedString length];
but it's not working. The count is always zero. How can I count the number of non-alphanumeric characters in an NSString object?
Thanks so much for your wisdom!
The problem with your approach is that you're not stripping the characters, you're trimming them. That means only stripping characters off the ends of the string that match the set (nothing in the middle).
For this you could iterate over the string and test that each character is not a member of the alphanumeric set. For example:
NSString* theString = // assume this exists
NSMutableCharacterSet* testCharSet = [[NSMutableCharacterSet alloc] init];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
NSUInteger length = [theString length];
NSUInteger totalNonAlnumCharacters = length;
for( NSUInteger i = 0; i < length; i++ ) {
if( [testCharSet characterIsMember:[theString characterAtIndex:i]] )
totalNonAlnumCharacters--;
}
NSLog(@"Number of non-alphanumeric characters in string: %lu", (long int)totalNonAlnumCharacters);
[testCharSet release];
Since you mentioned you tried it with stringByTrimmingCharactersInSet:, it might be interesting to learn that there actually is a way to do this only with framework calls. Borrowing the setup code from Jason
NSString* theString = // assume this exists
NSMutableCharacterSet* testCharSet = [[NSMutableCharacterSet alloc] init];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
you could then ditch the for loop by something like this:
NSArray *nonComp = [theString componentsSeparatedByCharactersInSet:testCharSet];
It would break the string apart at every index where it finds a char from the charset, creating an array of the remaining pieces. You could then use Key-Value Coding to then sum the length property of all the pieces:
NSNumber *numberOfNonANChars = [nonComp valueForKeyPath:@"@sum.length"];
or instead, glue the pieces together again and count the length:
NSUInteger nonANChars = [[nonComp componentsJoinedByString:@""] length];
But: splitting up the components will create an array and strings that are not needed after the counting - pointless memory allocation (the same goes for componentsJoinedByString:). And using valueForKeyPath: for this very simple summation also seems to be much more costly then just iterating over the original string.
The code might be a bit more object-oriented or even less error-prone, but in both cases performance will be orders of magnitude worse than Jason's code. So in this case, the good old for-loop will top misuse (as the used methods are not intended for this) of framework functionality.
NSString *str=@"str56we90";
int count;
for(int i=0;i<[str length];i++)
{
int str1=(int)[str characterAtIndex:i];
NSString *temp=[NSString stringWithFormat:@"%C",str1];
if(str1 >96 && str1 <123 || str1 >64 && str1 <91)
count=count +1;
}
int finalResult = [str length] - count;
count will be your final result.
精彩评论