微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在句子中查找一个单词 C++

如何解决在句子中查找一个单词 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;

这样的字符串

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。