如何搜索字符串中的单独单词,但排除组合单词? [英] How do search seperate words in a string, but exclude combined words ?

查看:59
本文介绍了如何搜索字符串中的单独单词,但排除组合单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我在代码中遇到了另一个错误.
我的代码段是这样的.

Hello All,
I ran accross another bug in my code.
my code snippet is something line this.

string MyLine = "The Fast Cars";
if(Myline.Contains("Fast"))
{
//do something.
}



在这种情况下,"if"语句为true.

现在,如果字符串,



in this case the "if" statement is true.

Now if the string,

MyLine = "The Fastest Cars"; or
MyLine = "The Fastest, Cars"; or
MyLine = "The xxFastest, Cars";



然后,上面的如果"条件将通过.
可以避免.



Then the above "if" condition will pass.
Can this be avoided.

推荐答案

使用此方法:
Use this method:
public static bool ContainsWord(string line, string word)
{
    return Regex.IsMatch(line, @"\b" + word + @"\b");
}


这是真的吗?

无论如何,假设您已修复代码,则必须在搜索的单词的两侧各留一个空格,以仅搜索整个单词.
How is it true ?

Anyhow assuming you fix the code, you''d have to put a space either side of the word you search for, to search for the whole word only.


另一种方法-您可以拆分将空格上的字符串(即空格)放入数组,然后遍历该数组以检查您要查找的确切字符串.
Another way - you could split your string on spaces (i.e. blanks) into an array and then go through that array to check the exact string you are looking for.


这篇关于如何搜索字符串中的单独单词,但排除组合单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆