gpt4 book ai didi

c# - 在不拆分的情况下在字符串中查找单词的任何方法

转载 作者:太空狗 更新时间:2023-10-29 21:28:54 25 4
gpt4 key购买 nike

我有一些字符串:

"rose with ribbon"
"roses in concrete"
"roses on bed"

我必须编写一个程序来查找存在首选词的字符串

例如:找到“on”所在的字符串,所以我只需要得到“roses on bed”。

我使用了这段代码:

foreach (KeyWord key in cKeyWords)
{
foreach (string word in userWords)
{
if (key.keyWord.IndexOf(word) != -1)
{
ckeyList.Add(key);
}
}
}

但我得到了所有字符串,因为 IndexOf 在所有字符串中都找到了“on”。

有没有其他解决方案可以在不拆分的情况下在字符串中找到单独的单词?也许可以使用 Linq 或 Regex?但我不擅长使用它们,所以最好有任何示例。

最佳答案

使用 \bon\b 的正则表达式应该可以做到这一点。

\bword boundary 的正则表达式 anchor , 因此正则表达式将匹配紧跟 on 紧接着另一个词边界的词边界。

以下 C# 示例...

string[] sArray = new string[]    {        "rose with ribbon",        "roses on bed",        "roses in concrete"    };Regex re = new Regex("\\bon\\b");foreach (string s in sArray){    Console.Out.WriteLine("{0} match? {1}", s, re.IsMatch(s));    Match m = re.Match(s);    foreach(Group g in m.Groups)    {        if (g.Success)        {            Console.Out.WriteLine("Match found at position {0}", g.Index);        }    }}

... 将生成以下输出:

rose with ribbon match? Falseroses on bed match? True    Match found at position 6roses in concrete match? False

关于c# - 在不拆分的情况下在字符串中查找单词的任何方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12439638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com