如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
How to create a function which finds a match of a word in a text including with skippings
我正处于第一步,目前正在做一个家庭作业项目(我实际上不需要发送,所以不急于得到答案......但无论如何都会很好(- (注意:我没有学到任何高级功能,我有存在(
我正在尝试编写一个程序来查找带有或不跳过字符的文本中的单词,并且"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;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 创建一个函数,返回给定单词在C++中的频率
- 字数统计函数在将单词添加到一组唯一单词时遇到问题
- 在C++中使用哪个函数来输入多个单词,比如C中的fgets
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 如何在函数中输入数字以输出单词?
- 尝试修复一个字符串函数,该函数采用字符串并通过替换一些单词来更改它
- 对于这个英语单词列表来说,什么是好的哈希函数?
- Qt C++macOS问题。我正在使用函数 .find( "a word") 在多集中搜索单词,它适用于 Windows 但不适用于 mac
- 函数允许单词,但不能短语C
- 如何用'auto'单词推导出哪种类型的参数编写函数?
- 为什么我的 forloop 在我的 lexical_words 函数中没有将字符串数组('keyWords")中的单词与字符串迭代器中的单词进行比较?
- 如何在c++中通过ifstream函数生成的文件中搜索特定的单词
- 在ARM体系结构中,C函数如何返回大小超过一个单词的值
- C++编写一个从段落中提取单词的函数
- C++ strtok 函数拆分单词
- 试图创建一个函数,将两个大小不等的字符串向量中的单词连接在一起
- 使用函数调用反转一个单词
- 英语单词的好哈希函数是什么?
- Wordwap函数修复保留单词之间的空白