这是我的句子:
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" } },
};
我需要将我的字符串拆分为一个字符串列表,其中集合中的字符串不存在,并将每个列表键放在它的位置,以便我知道我从哪个列表中找到列表的项目:
比如我这句话的输出是:
“1”、“问”、“1”、“问题”、“2”、“Over”、“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+"\"");
}
}
将导致:
" ask "
" questions on "
"Over"
".com"
您可以使用SelectMany
来展平您的集合
基于您的编辑:
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))
或任何类似的方法轻松删除它。
关于c# - 将字符串分隔到不在集合字典中的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50385671/