C# 检查word是否包含字符串列表中的子字符串
我见过使用linq这样做的例子:C# 检查word是否包含字符串列表中的子字符串,c#,regex,linq,C#,Regex,Linq,我见过使用linq这样做的例子: List<string> list = new List<string> {"One", "Two", "Three", "Four", "five", "six" }; string text = "OneTwoThreeFour"; list.Any(s => text.contains(s)) List List=新列表{“一”、“二”、“三”、“四”、“五”、“六”}; string text=“onetwotreefo
List<string> list = new List<string> {"One", "Two", "Three", "Four", "five", "six" };
string text = "OneTwoThreeFour";
list.Any(s => text.contains(s))
List List=新列表{“一”、“二”、“三”、“四”、“五”、“六”};
string text=“onetwotreefour”;
list.Any=>text.contains)
但这是否适用于所有可能的词语?意思是,如果我有一个由3个小词组成的大词(没有任何特殊字符分隔),它会抓住所有3个子词吗?或者一旦找到一个匹配项,就会停止检查吗
我想做的是用一个像“一二三四”这样的词,在每个唯一的词之间加一个空格或破折号,这样它的“一二三四”
有更好的方法吗
是否可以获取作为匹配项返回的“字符串”?更新以涵盖以下任一情况:
您可以从text
中获取单词列表,并按空格进行拆分。然后您可以使用SequenceEqual()
将该结果与list
进行比较
下面是一个例子:
static void Main(string[] args)
{
List<string> list = new List<string> {"One", "Two", "Three", "Four", "Five" };
string text = "OneTwoThreeFourFive";
string withSpaces = AddSpacesToSentence(text, true);
List<string> list2 = withSpaces.Split(' ').ToList();
bool b = list.SequenceEqual(list2);
}
// Refer to: https://stackoverflow.com/a/272929/4551527
static string AddSpacesToSentence(string text, bool preserveAcronyms)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
(preserveAcronyms && char.IsUpper(text[i - 1]) &&
i < text.Length - 1 && !char.IsUpper(text[i + 1])))
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
如果序列中的所有元素都满足谓词(此处为contains),则返回true
上面的代码段返回true。如果将“五”添加到
列表中(但保留文本相同),则返回false。一种简单的方法是迭代项目列表并执行字符串替换(我使用了StringBuilder
,您也可以使用字符串。替换),如:
List List=新列表{“一”、“二”、“三”、“四”、“五”、“六”};
string text=“onetwotreefour”;
StringBuilder sb=新的StringBuilder(文本);
foreach(列表中的var str)
{
替换(str,“+str+”);
}
字符串modifiedText=sb.ToString();
这将为您提供modifiedText=“一二三四”
。作为旁注,您不必检查列表中是否存在任何项目。如果列表中不存在该项,String.Replace
将不会执行任何操作
用于:
它能抓住所有3个子词吗?或者一旦它被激活,它会停止检查吗
找到一个匹配的
一旦找到匹配项,它将停止。您正在使用可枚举的。任何
,一旦找到匹配项,将不会执行进一步的比较 你能提供一个列表中包含的内容和你的文本的例子吗?
?请给我一分钟的时间,预期的输出是什么?问题已经在,我想把onetwotree-Four
变成onetwotree-Four
你有运行时可用的“所有可能的单词”字典吗?这些词是用大写字母表示的吗?您是否有计划区分“room”“plan”和“roomplan”这样的复合词?您的代码是“any”,如果文本列表中只有两个单词,该怎么办?
List<string> list = new List<string> {"One", "Two", "Three", "Four" };
string text = "OneTwoThreeFour";
list.All(s => text.Contains(s))
List<string> list = new List<string> { "One", "Two", "Three", "Four", "five", "six" };
string text = "OneTwoThreeFour";
StringBuilder sb = new StringBuilder(text);
foreach (var str in list)
{
sb.Replace(str, " " + str + " ");
}
string modifiedText = sb.ToString();