我正处于我的第一步,目前正在做一个家庭作业项目(实际上我不需要发送它,所以不急于得到答案......但无论如何都会很好) - (注意:我没有学习任何我认为存在的高级功能)
我正在尝试编写一个程序来在有或没有跳过字符的文本中查找单词,并且“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/