iphone - How can I count the number of non-alphanumeric characters in an NSString object? -


i'm diving ios development , i'm still getting familiar nsstring object. i'm @ point need count number of non-alphanumeric characters in string. 1 approach came stripping non-alphanumeric characters string, subtracting length of stripped string length of original string, so...

nscharacterset *nonalphanumericchars = [[nscharacterset alphanumericcharacterset ] invertedset];  nsstring *trimmedstring = [originalstring stringbytrimmingcharactersinset:nonalphanumericchars];  nsinteger numberofnonalphanumericchars = [originalstring length] - [trimmedstring length]; 

but it's not working. count zero. how can count number of non-alphanumeric characters in nsstring object?

thanks wisdom!

the problem approach you're not stripping characters, you're trimming them. means stripping characters off ends of string match set (nothing in middle).

for iterate on string , test each character not member of alphanumeric set. example:

nsstring* thestring = // assume exists nsmutablecharacterset* testcharset = [[nsmutablecharacterset alloc] init]; [testcharset formunionwithcharacterset:[nscharacterset alphanumericcharacterset]]; [testcharset formunionwithcharacterset:[nscharacterset whitespacecharacterset]]; nsuinteger length = [thestring length]; nsuinteger totalnonalnumcharacters = length; for( nsuinteger = 0; < length; i++ ) {   if( [testcharset characterismember:[thestring characteratindex:i]] )     totalnonalnumcharacters--; } nslog(@"number of non-alphanumeric characters in string: %lu", (long int)totalnonalnumcharacters); [testcharset release]; 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -