我不想用正斜杠分割字符串
我当前的代码如下所示:
string value = "Ctws Cwts/Rotc/Lts Ctws";
string[] tokens = value.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
Console.Write(token);
}
输出是这样的:"Cwts Cwts", "Rotc", "Lts Cwts"
现在我希望我的输出是这个:"Cwts", "Rotc", "Lts"
编辑:
一些答案表明我将使用 Distinct()
如果值为:"Something1 Cwts/Rotc/Lts Something2"
输出应该是一样的:"Cwts", "Rotc", "Lts"
最佳答案
只需使用 Distinct
string[] tokens = value
.Split(new char[] { '/', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Distinct();
也不要忘记在分隔符中包含空格
根据您的编辑,如果您想要这些值,您可以执行以下操作:所有输入的“Cwts”、“Rotc”、“Lts”
var values = new List<string> { "Cwts", "Rotc", "Lts" };
string[] tokens = value
.Split(new char[] { '/', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(t => values.Contains(t))
.Distinct();
关于c# - 用正斜杠分隔带空格和正斜杠的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21658079/