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

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

本文关键字:函数 单词 查找 包括跳 创建 何创建 一个 文本      更新时间:2023-10-16

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

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

我没有设法让代码更有效或更短,所以这就是寻求帮助的呼吁。

这是最短的 iv'e 获得该功能并使其实际工作

while (word[indexWord] != '' && text[indexText] != '' )
{
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] == '')
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] == '')
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"和从"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;
}