views:

302

answers:

3

How can I get the number of unique chars in my String?

Ex:

NSString *myString = @"Hello";

I want the count to be 4 and not 5.

I was trying to use the NSCharacterSet of myString and get the count but seems like it doesnt work.

NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:myString];

[myCharSet count];

Thanks for the tip.

A: 

try this:

NSString *myString = @"Hello"; NSRange range = NSMakeRange(location,length); NSString *myCharSet = [myString substringWithRange:range];

sandy
What are location and length in your code? What does obtaining a range substring have to do with counting unique characters?
Daniel Rinser
I dont get it? Can you please explain ur solution.
oceandrive
+1  A: 

A derivative of your code:

NSCharacterSet *myCharSet = [NSCharacterSet
              characterSetWithCharactersInString:@"Hello"];    
NSLog(@"Character Set Count: %d", [myCharSet count]);

Seems to work even though it issues a warning on compile. This prints "Character Set Count: 4" when I run it.

As an alternative an NSSet works such that it only allows unique values. You can add all of the characters to an NSSet and then get its count:

NSSet *set = [NSSet setWithArray:[@"H e l l o" 
                componentsSeparatedByString:@" "]];

NSLog(@"Set Count: %d", [set count]);

This prints "Set Count: 4"

Matt Long
A: 

Your code works for me. If you are trying to get [myCharSet count] later in another routine, it may be because myCharSet needs to be retained, and is originally set to autorelease.

mahboudz