繁体   English   中英

如何创建一个 function 在文本中找到匹配的单词,包括跳过

[英]How to create a function which finds a match of a word in a text including with skippings

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

我正在尝试编写一个程序来在文本中查找带有或不带有跳过字符的单词,并且'main'中的 output 是在'text'中找到的'word'的每个字符之间的空格

我没有设法让代码更高效或更短,所以这就是求助的电话。

这是最短的,我得到了 function 并让它真正工作

 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' 到 'o' 跳过了 2,从 '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;
}

暂无
暂无

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

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