查找字符串的子字符串
Finding substring of string
所以,我刚刚开始这门C++课程,我们现在正在做字符串。对于这个作业,我的教授要我做的是在字符串中找到一个字符串,并将其打印出来并放在某个位置。这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Please enter a phrase: " << endl;
string phrase;
getline(cin, phrase);
cout << "Please enter a possible substring of the phrase: " << endl;
string phrase_2;
getline(cin, phrase_2);
string pos = phrase.substr(phrase_2);
cout << phrase_2 << "was found at position " << pos << endl;
return 0;
}
我已经尝试了好几个小时,试图让代码打印出位置。这可能是完全错误的,我为此道歉,但如果你能帮助我,我将不胜感激。
你需要使用 std::string::find 来获取子字符串在字符串中的位置:
以您的代码为例:
int main ()
{
cout << "Please enter a phrase: n";
string phrase;
getline(cin, phrase);
cout << "Please enter a possible substring of the phrase: n";
string phrase_2;
getline(cin, phrase_2);
std::size_t position = phrase.find(phrase_2);
if (position != std::string::npos)
std::cout << phrase_2 << " was found at position " << position << "n";
return 0;
}
谷歌是你的朋友...
而不是
string pos = phrase.substr(phrase_2);
你应该使用
size_t pos = phrase.find(phrase_2);
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分