在句子中查找单词 c++

问题描述 投票:0回答:2

此代码应该说明句子中是否存在单词。当我插入句子和声明字符串的单词时(例如:字符串 s =“the cat is on the table”字符串 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;
   }

  }
}
c++ string getline
2个回答
1
投票

获取输入字符串后,然后使用

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;


0
投票

只需使用查找即可。

https://cplusplus.com/reference/string/string/find/

示例

std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");

// different member versions of find in the same order as above:

std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';

示例结束

将您的测试字符串和目标子字符串输入其中,如果子字符串存在,它就会吐出。快速又简单。

© www.soinside.com 2019 - 2024. All rights reserved.