user143015
user143015

Reputation:

How to get count of Unique chars in a string

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.

Upvotes: 1

Views: 1006

Answers (3)

Sandeep Kumar
Sandeep Kumar

Reputation: 1605

try this:

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

Upvotes: 0

mahboudz
mahboudz

Reputation: 39376

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.

Upvotes: 0

Matt Long
Matt Long

Reputation: 24476

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"

Upvotes: 2

Related Questions