c# 过滤字符串中的重复字符

时间:2023-12-28 22:02:08

有字符串"a,s,d,v,a,v",如果想去除其中重复的字符,怎么做?

下面是一个方法,用Hashtable来记录唯一字符,排除重复字符,仅供参考。

1.过滤方法:

public class OperationString
{
/// <summary>
/// 过滤字符串中的重复字符
/// </summary>
/// <param name="str">要过滤的字符串</param>
/// <returns>返回过滤后的字符串</returns>
public string FilterRepetitionChar(string sourceStr)
{
string returnStr = string.Empty;
string[] strList = sourceStr.Split(',');
Hashtable ht = new Hashtable();
foreach (string strChar in strList)
{
if (!ht.ContainsKey(strChar))
{
ht.Add(strChar, strChar);//这里让ht的key和value值相等,不影响下面的程序
returnStr += strChar + ",";//字符以逗号分隔
}
}
returnStr = returnStr.Trim(',');//去掉最后一个逗号
return returnStr;
}
}

2.程序入口:

class Program
{
static void Main(string[] args)
{
string sourceString = "a,b,c,d,a,b";
string newString = string.Empty; OperationString os = new OperationString();
newString = os.FilterRepetitionChar(sourceString); Console.WriteLine("过滤前的字符串:" + sourceString);
Console.WriteLine("----------------------------------");
Console.WriteLine("过滤后的字符串:" + newString); Console.ReadKey();
}
}

3.运行结果:

过滤前的字符串:a,b,c,d,a,b

----------------------------------
过滤后的字符串:a,b,c,d