更新:感谢您的回答,但我不同意我的问题已由另一个帖子回答。 “多个分隔符”和“多字符分隔符”是两个不同的问题。
到目前为止,这是我的代码:
List<string> delimiters = new List<string>();
List<string> data = new List<string>
{
"Car|cBlue,Mazda~Model|m3",
//More data
};
string userInput = "";
int i = 1;
//The user can enter a maximum of 5 delimiters
while (userInput != "go" && i <= 5)
{
userInput = Console.ReadLine();
delimiters.Add(userInput);
i++;
}
foreach (string delimiter in delimiters)
{
foreach (string s in data)
{
//This split is not working
//string output[] = s.Split(delimiter);
}
}
因此,如果用户输入“| c”和“〜”,则预期输出为:“Car”,“Blue,Mazda”,“Model | m3”
如果用户输入“| c”,“| m”和“,”,则预期输出将为:“Car”,“Blue”,“Mazda~Model”,“3”
答案 0 :(得分:3)
String.Split
有一个超载就是这样 - 您只需要将List<string>
转换为string[]
:
string input = "Car|cBlue,Mazda~Model|m3";
List<string> delims = new List<string> {"|c", "~"};
string[] out1 = input.Split(delims.ToArray(),StringSplitOptions.None);
//output:
// Car
// Blue,Mazda
// Model|m3
delims = new List<string> {"|c", "|m", ","};
string[] out2 = input.Split(delims.ToArray(),StringSplitOptions.None).Dump();
//output:
// Car
// Blue
// Mazda~Model
// 3
答案 1 :(得分:3)
将用户输入添加到List delimiters。
string data = "Car|cBlue,Mazda~Model|m3";
List<string> delimiters = new List<string>();
delimiters.Add("|c");//Change this to user input
delimiters.Add("|m");//change this to user input
string[] parts = data.Split(delimiters.ToArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string item in parts)
{
Console.WriteLine(item);
}
答案 2 :(得分:2)
您可以使用SelectMany
获取所有data
字符串和ToArray()
方法的结果,以便从delimiters
var result = data.SelectMany(s => s.Split(delimiters.ToArray(), StringSplitOptions.None));