如何获取字符串中唯一字符的数量?
How can I get the number of unique chars in my String?
例如:
NSString * myString = @"Hello";
NSString *myString = @"Hello";
我希望计数为4,而不是5.
I want the count to be 4 and not 5.
我试图使用myString的NSCharacterSet来获取计数,但似乎不起作用.
I was trying to use the NSCharacterSet of myString and get the count but seems like it doesnt work.
NSCharacterSet * myCharSet = [NSCharacterSet characterSetWithCharactersInString:myString];
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:myString];
[myCharSet计数];
[myCharSet count];
感谢小费.
推荐答案您的代码的派生形式:
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"Hello"]; NSLog(@"Character Set Count: %d", [myCharSet count]);即使它在编译时发出警告,也似乎可以工作.当我运行它时,它会打印字符集计数:4".
Seems to work even though it issues a warning on compile. This prints "Character Set Count: 4" when I run it.
作为替代,NSSet的工作方式是仅允许唯一值.您可以将所有字符添加到NSSet中,然后获取其计数:
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]);这将显示设置计数:4"
This prints "Set Count: 4"
更多推荐
如何获取字符串中唯一字符的计数
发布评论