在句子中查找单词 C++
Find a word in a sentence c++
这段代码应该说明一个词是否出现在句子中。当我在声明字符串的位置插入句子和单词时(例如:string s = "the cat is on the table" string p = "table" 程序说这个词在句子)代码有效,但是对于 getline,for 循环永远不会开始,它总是说这个词不在句子中。
请帮助我不知道该怎么做
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}
获取输入字符串后使用 length()
计算长度,否则您获取的不是字符串的实际大小。
getline(cin, s);
getline(cin, p);
int sl = s.length();
int pl = p.length();
要在 getline()
获取输入字符串后拆分单词,您可以使用 stringstream
这是一个内置的 c++ 函数,例如:
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
while(ss >> word){
// your desired strings are in `word` one by one
cout << word << "\n";
}
}
另一件事是你可以声明像 string s, p, word;
这样的字符串
这段代码应该说明一个词是否出现在句子中。当我在声明字符串的位置插入句子和单词时(例如:string s = "the cat is on the table" string p = "table" 程序说这个词在句子)代码有效,但是对于 getline,for 循环永远不会开始,它总是说这个词不在句子中。
请帮助我不知道该怎么做
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}
获取输入字符串后使用 length()
计算长度,否则您获取的不是字符串的实际大小。
getline(cin, s);
getline(cin, p);
int sl = s.length();
int pl = p.length();
要在 getline()
获取输入字符串后拆分单词,您可以使用 stringstream
这是一个内置的 c++ 函数,例如:
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
while(ss >> word){
// your desired strings are in `word` one by one
cout << word << "\n";
}
}
另一件事是你可以声明像 string s, p, word;