如何获取字符串中唯一字符的计数

编程入门 行业动态 更新时间:2024-10-18 01:39:21
本文介绍了如何获取字符串中唯一字符的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何获取字符串中唯一字符的数量?

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"

更多推荐

如何获取字符串中唯一字符的计数

本文发布于:2023-11-29 12:36:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   中唯一

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!