计算字符串中两个单词的出现次数
本文关键字:单词 两个 字符串 计算 | 更新日期: 2023-09-27 18:23:44
我需要能够在给定范围内找到字符串中两个单词的出现次数。给定两个关键字和范围,返回在给定范围内存在的关键字的出现次数。例如,具有以下字符串(关键字也包括在范围中):
input string:
"on top on bottom on side Works this Magic door"
input filters: "on", "side", range: 6
(范围6意味着,在我们搜索的这两个单词之间最多可以有四个其他单词)
output should be: 3
(因为"on"answers"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;