static void Main()
{
string myString = "You ask your questions on StackOverFlow.com";
string[] collection = new string[]
{
"You",
"your",
"Stack",
"Flow"
};
var splitted = myString.Split(collection, StringSplitOptions.RemoveEmptyEntries);
foreach(var s in splitted)
{
Console.WriteLine("\""+s+"\"");
}
}
将导致:
" ask "
" questions on "
"Over"
".com"
您可以使用SelectMany 来扁平化您的collections
根据您的编辑:
static void Main()
{
string myString = "You ask your questions on StackOverFlow.com";
Dictionary<int, List<string>> collections = new Dictionary<int, List<string>>()
{
{ 1, new List<string>() { "You", "your" } },
{ 2, new List<string>() { "Stack", "Flow" } },
};
foreach(var index in collections.Keys)
{
foreach(var str in collections[index])
{
myString = myString.Replace(str, index.ToString());
}
}
Console.WriteLine(myString);
}
给予:
1 ask 1 questions on 2Over2.com
static void Main()
{
string myString = "You ask your questions on StackOverFlow.com";
Dictionary<int, List<string>> collections = new Dictionary<int, List<string>>()
{
{ 1, new List<string>() { "You", "your" } },
{ 2, new List<string>() { "Stack", "Flow" } },
};
var tempColl = collections.SelectMany(c => c.Value);
// { "You", "your", "Stack", "Flow" }
string separator = String.Join("|", tempColl);
// "You|your|Stack|Flow"
var splitted = Regex.Split(myString, @"("+separator+")");
// { "", "You", " ask ", "your", " questions on ", "Stack", "Over", "Flow", ".com" }
for(int i=0;i<splitted.Length;i++)
{
foreach(var index in collections.Keys)
{
foreach(var str in collections[index])
{
splitted[i] = splitted[i].Replace(str, index.ToString());
}
}
}
foreach(var s in splitted)
{
Console.WriteLine("\""+s+"\"");
}
}
给予:
""
"1"
" ask "
"1"
" questions on "
"2"
"Over"
"2"
".com"
注意开头的空字符串是because
如果在输入字符串的开头或结尾找到匹配项,
一个空字符串包含在开头或结尾
返回数组。
但您可以使用.Where(s => !string.IsNullOrEmpty(s)) 或类似的方式轻松删除它。