How to get count of Unique chars in a string

江枫思渺然 提交于 2019-12-24 12:05:04

问题


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.


回答1:


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"




回答2:


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.




回答3:


try this:

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


来源:https://stackoverflow.com/questions/1322070/how-to-get-count-of-unique-chars-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!