[英]Searching for a word in cstring text (1-D array/c++)
I'm practicing 1-D array and the question asks from the user to input a line of text and then input a word that the user wants to search and find out how many times it's repeated in the line of text. 我正在练习一维数组,该问题要求用户输入一行文本,然后输入一个用户想要搜索的单词,并找出该单词在文本行中重复了多少次。 It doesn't have to be a separated by spaces and can be in a word (ie 'go' in 'goalkeeper').
它不必用空格隔开,也可以用一个单词(即“ goalkeeper”中的“ go”)来表示。
My problem is creating a proper if condition in the loop that searches through the sentence. 我的问题是在循环搜索句子的循环中创建适当的if条件 。 Thing is, my line variable is char (
char line[200];
) while my word variable was string ( string word;
) so my program gave me an error when I wrote a condition in the loop that went like this: 问题是,我的行变量是char (
char line[200];
),而我的word变量是string ( string word;
),所以当我在循环中编写如下条件时,程序给了我一个错误:
if ( line[i] == word)
Then I tried changing the word variable to char and created a loop to get the input but then I got stuck with how to work out the loop that searches through the line of text. 然后,我尝试将word变量更改为char并创建了一个循环以获取输入,但是随后我陷入了如何计算循环搜索文本行的问题。
I just want some pointers. 我只想要一些指针。 This is my current code so far (it's a mess):
到目前为止,这是我当前的代码(很混乱):
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
char liner[200], word[200];
int i, counter1 = 0, counter2 = 0;
cout<<"Enter a line of text: ";
cin.get (liner, 200);
cout<<"Enter a word to search: ";
for (i = 0; word[i] != ' '; i++)
{
cin>>word[i];
}
cout<<endl;
for (i = 0; i < 200; i++)
{
if (liner[i] == word[t])
{
counter2++;
}
}
cout<<word<<" was found "<<counter2<<" times."<<endl;
return 0;
}
One possible solution is to use strncmp, which compares 2 strings up to the specified length to see if they are equal (stopping when end of either is reached or number of chars have been compared). 一种可能的解决方案是使用strncmp,它比较2个字符串,直到指定的长度为止,以查看它们是否相等(达到两个字符串的末尾或比较了字符数时停止)。
So, the code would be something like: 因此,代码将类似于:
int main()
{
char liner[200], word[200];
int i, counter1 = 0, counter2 = 0;
cout<<"Enter a line of text: ";
cin.getline(liner, 200);
cout<<"Enter a word to search: ";
cin.getline(word, 200);
cout<<endl;
int lineLen = strlen(line);
int wordLen = strlen(word);
for (i = 0; i < lineLen && I < wordLen; i++)
{
if (strncmp(&line[i], word, wordLen)
{
counter2++;
}
}
cout<<word<<" was found "<<counter2<<" times."<<endl;
return 0;
}
To improve the program, you can try not using a fixed size array, but read the data into a std::string. 为了改进程序,您可以尝试不使用固定大小的数组,而是将数据读取到std :: string中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.