包含方法 returns 错误值

contains method returns wrong value

我正在使用 Contains() 检查一个字符串是否有一个词,该方法返回 true 但没有我正在比较的词。

正文:

“Under the guise of Medicare for All and a Green New Deal, Democrats are embracing the same tired economic theories that have impoverished nations and stifled the liberties of millions over the past century,” Pence said to applause. “That system is socialism.

“And the only thing green about the so-called Green New Deal is how much green it’s going to cost taxpayers if we do it: million,” he said. Democrats have said the price tag would be lower than the figure Pence quoted.

His comments to the Conservative Political Action Conference outside Washington continued a White House and Republican National Committee push to paint the opposition party as hellbent on making America’s economy one that is centrally planned from Washington and intent on taking money out of Americans’ pockets to finance a myriad social programs."

搜索词:“民族”

您知道进行该搜索的另一种方法吗?

您的搜索返回 true,因为文本包含 "nations",其中包括字符串 "nation".

如果您要搜索 "nation" 并且不包括类似词 "nations",最简单的方法可能是使用正则表达式和 \b元字符,匹配单词边界。

bool found = Regex.IsMatch(text, @"\bnation\b");

如果你想概括这个,你可以写:

string search = "nation";
bool found = Regex.IsMatch(text, $@"\b{Regex.Escape(search)}\b");

正如@Flydog57 在评论中有用地指出的那样,如果这是您所追求的,您也可以进行不区分大小写的搜索:

string search = "nation";
bool found = Regex.IsMatch(text, $@"\b{Regex.Escape(search)}\b", RegexOptions.IgnoreCase);

正则表达式有它的问题,因为您需要非常深入地了解它的机制是如何工作的,并且发生事故或性能噩梦的可能性很大。 我通常做的是将文本分解成小块并使用它们。

随时向 Split() 方法添加内容!享受:

static bool findWord()
{
 var text = @"“Under the guise of Medicare for All and a Green New Deal, Democrats are embracing the same tired economic theories that have impoverished nations and stifled the liberties of millions over the past century,” Pence said to applause. “That system is socialism.

“And the only thing green about the so-called Green New Deal is how much green it’s going to cost taxpayers if we do it:  million,” he said. Democrats have said the price tag would be lower than the figure Pence quoted.

His comments to the Conservative Political Action Conference outside Washington continued a White House and Republican National Committee push to paint the opposition party as hellbent on making America’s economy one that is centrally planned from Washington and intent on taking money out of Americans’ pockets to finance a myriad social programs.";

var stringList = text.Split(' ', ',', ':', '.', '?', '“', '-'); // split the text into pieces and make a list
foreach (var word in stringList) // go through all items of that list
{
  if (word == "nation") return true;       
}
return false;
}