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+"\"");
}
}
will result in:
" ask "
" questions on "
"Over"
".com"
You can use SelectMany
to flatten your collections
Based on your edit:
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);
}
Gives:
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+"\"");
}
}
Gives:
""
"1"
" ask "
"1"
" questions on "
"2"
"Over"
"2"
".com"
Note the empty string at the beginning is because
If a match is found at the beginning or the end of the input string,
an empty string is included at the beginning or the end of the
returned array.
But you can easily remove it using either .Where(s => !string.IsNullOrEmpty(s))
or anything alike.