c++ - 如何创建一个函数来查找文本中单词的匹配项,包括跳过

标签 c++ arrays search

我正处于我的第一步,目前正在做一个家庭作业项目(实际上我不需要发送它,所以不急于得到答案......但无论如何都会很好) - (注意:我没有学习任何我认为存在的高级功能)

我正在尝试编写一个程序来在有或没有跳过字符的文本中查找单词,并且“main”中的输出是在“文本”中找到的“单词”的每个字符之间的空格

我无法使代码更高效或更短,所以这就是寻求帮助的原因。

这是最短的 iv'e 得到了功能并让它实际工作

 while (word[indexWord] != '\0' && text[indexText] != '\0' )
 {
    if (word[indexWord] == text[indexText])
    {
        indexWord++;
        indexText++;

        if (firstSame)
        {
            arr[i++] = space; // saving all spaces
            space = -1;
        }

    firstSame=true;//counting spaces only after first found
    }
    else if (word[indexWord] == '\0')
        break;
    else
        indexText++;

    if (firstSame)
        space++;
}

i--;

int sum = 0, sum2 = 0;
while (i > 0 && sum == sum2)// checking that all spaces are equal
{
    sum = arr[i--];
    sum2 = arr[i];
}
if (i==0 && sum == sum2 && word[indexWord] == '\0')
    return sum;
else
    return -1;

main() 中的程序示例,如果正常工作,它应该是什么样子:

Please enter a sentance:
Hello to you
Please enter a word to find in sentance:
eoo
The count of spaces is: 2

结果是 2 因为从 'e' 跳过了 2 到 'o' 与 'o' 到下一个 'o' 相同

如果要在文本中查找的词如下:

Please enter a sentance:
yesterday
Please enter a word to find in sentance:
xs
The count of spaces is: -1

结果为-1,因为没有匹配。

最佳答案

将距离保存在数组中的想法是对的,但你会发现实际上并不需要数组,只需将前两个匹配字符之间的距离保存在 text 并检查后续距离是否相同,同时在单个循环中遍历两个字符串。

int solve(string text, string word) {
  if (word.size() > text.size()) return -1;
  int skipVal = -1;
  int j = 0;
  for (int i = 0, last = -1; i < text.size() && j < word.size(); i++) {
    if (text[i] == word[j]) {
      if (last != -1) {
        int dist = i - last - 1;
        if (skipVal == -1) {
          skipVal = dist;
        } else if (dist != skipVal) {
          return -1;
        }
      }
      last = i;
      j++;
    }
  }
  if (j < word.size())
    return -1;
  return skipVal;
}

关于c++ - 如何创建一个函数来查找文本中单词的匹配项,包括跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053628/

相关文章:

c++ - IE 地址栏搜索。我需要在当前结果列表的末尾添加其他结果列表

javascript - 如何创建一个搜索栏,用于下拉 SQL 数据库中的元素列表

c++ - 我如何才能加速此代码(MWE!),例如使用限制

C++ - 精确时间 vector

php - 从数据库中获取多个字段到数组

sql - 查询postgres中的文本数组

c++ - `x` 的所有元素是否都存在于 `y`(已排序 vector )中?

c++ - 是一个函数指针 odr-如果它被调用

c++ - MessageBox C++ 错误

javascript - 循环遍历数组并过滤电子邮件