C# 去除字符串中的重复字符
可以使用 HashSet 来判断字符串中是否有重复字符,并且可以直接将重复的字符串去掉。
示例代码:
string str = 'hello world';
HashSet<string> set = new HashSet<string>();
string result = '';
foreach (char c in str)
{
string s = c.ToString();
if (!set.Contains(s))
{
set.Add(s);
result += s;
}
}
Console.WriteLine(result);
输出结果为:
helo wrd
解释:
首先定义一个字符串和一个 HashSet 集合对象。然后遍历字符串的每一个字符,将其转换为字符串类型。如果 HashSet 中不包含该字符串,就将其添加到 HashSet 中,并将其加入到结果字符串中。如果 HashSet 中已经包含该字符串,就不需要再添加了。
最终输出的结果字符串中,重复的字符已经被去掉了。
原文地址: https://www.cveoy.top/t/topic/oDnj 著作权归作者所有。请勿转载和采集!