如何计算字符串中的唯一字符

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

假设我们有变量 myString="blabla" 或 mystring=998769

Lets say we have variable myString="blabla" or mystring=998769

myString.Length; //will get you your result myString.Count(char.IsLetter); //if you only want the count of letters:

如何获得,唯一字符数?我的意思是blabla"结果必须为 3,998769"将是 4.是否准备好运行功能?有什么建议吗?

How to get, unique character count? I mean for "blabla" result must be 3, doe "998769" it will be 4. Is there ready to go function? any suggestions?

推荐答案

你可以使用LINQ:

var count = myString.Distinct().Count();

它使用了一个事实,即 string 实现了 IEnumerable<char>.

It uses a fact, that string implements IEnumerable<char>.

没有 LINQ,您可以在内部执行 Distinct 的相同操作并使用 HashSet:

Without LINQ, you can do the same stuff Distinct does internally and use HashSet<char>:

var count = (new HashSet<char>(myString)).Count;

更多推荐

如何计算字符串中的唯一字符

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

发布评论

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

>www.elefans.com

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