接受用户的一些文字。接受需要搜索的字符串。您的程序应该打印在文本中找到的字符串的出现次数以及找到该模式的位置。请查看以下示例输出:
我的功能
我不知道我做错了什么,我需要帮助!
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;
}
}
}
}
答案 0 :(得分:0)
第一个文本和搜索未初始化为itext和word。 第二个你应该是==而不是=。 第三,你的检查方法是错误的,这是你需要弄清楚的事情(你需要做你的功课)。
答案 1 :(得分:0)
首先,您无法创建具有动态长度的数组。
其次,我们在比较两个值时在==
语句中使用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
}
}
答案 2 :(得分:0)
这应该为您提供一些方法,可以根据您的代码解决问题。
删除了char数组。因为没有初始化而且不需要。
内部循环应该只有一个,你可以判断是否找到了单词。
要阅读整篇句子,您需要使用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
答案 3 :(得分:0)
我不会为你做你的硬件,但是我会给出一些可以帮助你到达那里的指示。
char text[itext.length()];
char search[word.length()];
这没有任何意义。我甚至不确定它是否合法,但如果是的话,它仍然是一个坏主意,因为你的空终结器没有空间。此外,您已将值存储在itext
和word
中,那么为什么要将它们放在其他位置?
string
有一个find方法(string::find)尝试使用找到从零开始的实例,然后在找到的位置再次搜索+ 1.重复搜索直到搜索失败。