這是我的一句話:
You ask your questions on StackOverFlow.com
現(xiàn)在我有一個字符串列表的字典集合:
Dictionary<int, List<string>> collections = new Dictionary<int, List<string>>()
{
{ 1, new List<string>() { "You", "your" } },
{ 2, new List<string>() { "Stack", "Flow" } },
};
我需要將我的字符串拆分為字符串列表,其中集合中的字符串不在那里,并將每個List鍵放在其位置,以便我知道從哪個列表中找到列表的項目:
例如,我的句子的輸出是:
“1”,“問”,“1”,“問題”,“2”,“結(jié)束”,“2”,“.com”
正如您所看到的,此處未列出集合中的所有單詞.相反,他們的列表的密鑰被替換. 我所知道的是,我可以通過以下代碼檢查我的字符串是否包含其他列表中的任何單詞:
listOfStrings.Any(s=>myString.Contains(s));
但是不知道如何檢查整個字典的列表集合并獲取每個列表鍵并將其替換為新的字符串列表. 解決方法:
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 "\"");
}
}
將導(dǎo)致:
" ask "
" questions on "
"Over"
".com"
您可以使用SelectMany來展平您的館藏
根據(jù)您的編輯:
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
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.
但你可以使用.Where(s =>,!string.IsNullOrEmpty(s))或類似的東西輕松刪除它. 來源:http://www./content-1-238551.html
|