获取字符串 c# 中字母的出现次数
本文关键字:字符串 获取 | 更新日期: 2023-09-27 17:57:21
>我有一个字符串,看起来像
E-1,E-2,F-3,F-1,G-1,E-2,F-5
现在我想要数组中的输出,例如
E, F, G
我只想要字符串中出现的字符名称一次。
我的代码示例如下
string str1 = "E-1,E-2,F-3,F-1,G-1,E-2,F-5";
string[] newtmpSTR = str1.Split(new char[] { ',' });
Dictionary<string, string> tmpDict = new Dictionary<string, string>();
foreach(string str in newtmpSTR){
string[] tmpCharPart = str.Split('-');
if(!tmpDict.ContainsKey(tmpCharPart[0])){
tmpDict.Add(tmpCharPart[0], "");
}
}
有没有简单的方法可以在 c# 中使用字符串函数来做到这一点,如果是,如何
string input = "E-1,E-2,F-3,F-1,G-1,E-2,F-5";
string[] splitted = input.Split(new char[] { ',' });
var letters = splitted.Select(s => s.Substring(0, 1)).Distinct().ToList();
也许你可以用正则表达式获得相同的结果! :-)