如何解决我怎样才能得到句子而不是单词?我想在 C++ 中通过 strstr 在第一个字符串中搜索第二个字符串
我想通过从用户那里获取字符串来搜索第一个字符串中的第二个字符串。但是 cin
由于空格而不适用于句子。如何获取一个字符串作为一个句子,然后在该句子中搜索第二个字符串?
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
string str;
cin>>str;
string target;
cin>>target
char *p = strstr(str,target);
if (p)
cout << "'" << target << "' is present in \"" << str << "\" at position " << p-str;
else
cout << target << " is not present \"" << str << "\"";
return 0;
}
https://onlinegdb.com/S1IVrTVHO
解决方法
但是 cin
由于空格对句子不起作用。
std::cin
不关心空格,operator>>
关心。阅读句子时只需使用 std::getline(cin,str)
而不是 cin >> str
。
此外,您应该使用 std::string::find()
而不是 strstr()
。
试试这个:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin,str);
string target;
cin >> target;
string::size_type p = str.find(target);
if (p != string::npos)
cout << "'" << target << "' is present in \"" << str << "\" at position " << p;
else
cout << "'" << target << "' is not present in \"" << str << "\"";
return 0;
}
,
如果您想获得整行,请使用 getline()
中的 <string>
。
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin,str);
string target;
getline(cin,target);
const char* p = strstr(str.c_str(),target.c_str());
if (p)
cout << "'" << target << "' is present in \"" << str << "\" at position " << p - str.c_str();
else
cout << target << " is not present \"" << str << "\"";
return 0;
}
.c_str
将 std::string
转换为 C-Style 字符串,这样 strstr
只接受 C-Style 字符串,可以执行它的操作。此外,在您的原始代码中,您忘记用 cin>>target
终止 ;
。
std::cin
是输入的来源。 >>
运算符从 std::cin
获取一些内容,直到空格为止。如果您需要整行,请使用 std::getline(cin,str)
而不是 cin >> str
。 std::getline()
从 std::cin
读取直到遇到换行符,因此它更适合您的目的。 (std::getline
将 istream
(如 std::cin
)作为其第一个参数,并将其结果作为第二个参数使用 std::string
。)
另外,以后可能会考虑使用其他方法在字符串中查找字符串,而不是使用strstr()
,因为这是针对C风格的字符串,对于更多的C++风格的子字符串查找,可能会有更好的选择。
再见!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。