C++帮助:使用数组和循环在文本中查找单词
C++ Help: Finding words in text with arrays and loops
接受来自用户的一些文本。接受需要搜索的字符串。您的程序应该打印在文本中找到的字符串的出现次数,以及找到模式的位置。查看以下示例输出:
对于我的函数
我不知道我做错了什么,我需要帮助!
void getText()
{
string itext, word;
int position;
bool done = false;
cout << "Enter some text" << endl;
cin >> itext;
cout << "Enter the word or phrase to wish to find" << endl;
cin >> word;
char text[itext.length()];
char search[word.length()];
for(int i = 0; i < itext.length(); i++)
{
for(int j = 0; j < word.length(); j++)
{
if(text[i] = search[j])
{
position = i;
cout << position;
}
}
}
}
第一个文本和搜索不会初始化为 itext 和 word。其次,您的 if 应该是 == 而不是 = 。第三,你的检查方法是错误的,这是你需要弄清楚的(你需要做功课)。
我不会为你做硬件,但我会给出一些应该可以帮助你到达那里的指示。
char text[itext.length()];
char search[word.length()];
这是没有道理的。我什至不确定它是否合法,但如果是,这仍然是一个坏主意,因为您将没有空间容纳您的空终止符。此外,您已经将值存储在 itext
和 word
中,那么为什么要将它们放在其他地方呢?
string
有一个查找方法(字符串::find)尝试使用它查找从零开始的实例,然后在找到的位置 + 1 处再次搜索。重复此操作,直到搜索失败。
首先,你不能创建具有动态长度的数组。
其次,我们在比较两个值时if
语句中使用==
。
最后,在这里我使用string.find("searchPhrase", startIndex)
重新编码您的解决方案。 希望对您有所帮助。
#include <iostream>
#include <string>
using namespace std;
void getText()
{
string itext, word;
int position;
bool done = false;
cout << "Enter some text" << endl;
cin >> itext;
cout << "Enter the word or phrase to wish to find" << endl;
cin >> word;
int startIndex = 0 ;
while( itext.find(word,startIndex) != -1)
{
cout<<"Found at "<<itext.find(word,startIndex)<<endl;
startIndex = itext.find(word,startIndex) + 1; // we update start point of next seatch
}
}
这应该为您提供一些基于代码解决它的选项的方向。
字符数组已删除。 因为未初始化,也不需要。
内部循环应该结束,然后你才能判断是否找到了单词。
要阅读整个句子,您需要使用getline。
比较是通过使用==
而不仅仅是=
。我更喜欢!=
这意味着不平等。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text, word;
int position;
bool done = false;
cout << "Enter some text" << endl;
getline(cin, text); //if you want line with white spaces...
cout << "Enter the word or phrase to wish to find" << endl;
cin >> word;
size_t i,j;
for(i = 0; i < text.length(); i++)
{
for(j = 0; j < word.length(); j++)
{
if(text[i+j] != word[j])
{
break;//inner for
}
}
if(j == word.length()){ //means inner loop run till the end.
position = i;
cout << position<<endl;
}
}
return 0;
}
输出:
Enter some text
abcd abc abcd
Enter the word or phrase to wish to find
abc
0
5
9
相关文章:
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 如何从文本文件中查找最常见的字母和出现次数?
- 在文本中查找半个单词"ABBA"的问题
- 在C++中查找文本中的模式
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 如何创建一个函数,该函数在文本中查找单词的匹配项,包括跳过
- 在大型 JSON 文件中查找文本
- 尝试在自定义 QT 创建器文本编辑器中创建查找和替换循环.我似乎无法设置光标位置
- 文本文件中的电话号码查找
- 如何在没有分隔符的大文本文件中查找所有字典单词
- C++查找文本和计数出现次数
- 在文本文件 C++ 中查找( ")
- Visual Studio,在(解决方案资源管理器的)某个筛选器内的所有文件中查找/替换文本
- 查找字符在标准输入文本中出现的次数
- 如何将文本(诗歌)拆分为行(字符串/字符[])并查找每个行的最后一个单词
- 文本处理以查找字符串的共存
- 使用 TinyXML 查找特定的文本值
- QTreeWidgetItem 通过文本查找子项
- 查找页面上文本的坐标-c++,windows,VS2013
- 如何做一个换行的文本查找器