繁体   English   中英

计算一个字符串中两个单词出现的次数

[英]Count number of occurrences of two words in a string

我需要能够找到给定范围内字符串中两个单词的出现次数。 给定两个关键字和范围,返回次数出现关键字在给定范围内。 因此,例如,具有以下字符串(范围内也包含关键字):

input string:
    "on top on bottom on side Works this Magic door"

input filters: "on", "side", range: 6

(范围6表示,我们搜索的两个词之间最多可以有四个其他词)

output should be: 3 

(因为“ on”和“ side”的匹配发生了3次。

范例2:

input string:
    "on top on bottom on side Works this Magic door"

input filters: "on", "side", range: 3

output should be: 1

我已经尝试过此正则表达式“ \\bon\\W+(?:\\w+\\W+){1,6}?side\\b “,但这不会返回预期的输出。 我不确定“ regex”是否正确。

您的正则表达式对于范围8是正确的。问题是匹配项重叠,无法一次搜索完成。 您必须执行以下操作:

string s = "on top on bottom on side Works this Magic door";
Regex r = new Regex(@"\bon\W+(?:\w+\W+){0,4}side\b");
int output = 0;
int start = 0;
while (start < s.Length)
{
    Match m = r.Match(s, start);
    if (!m.Success) { break; }
    Console.WriteLine(m.Value);
    output++;
    start = m.Index + 1;
}
Console.WriteLine(output);

尝试这个

            string input = "on top on bottom on side Works this Magic door";
            List<string> array = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            int onIndex = array.IndexOf("on");
            int sideIndex = array.IndexOf("side");

            int results = sideIndex - onIndex - 1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM