查找字符串的子字符串

Finding substring of string

本文关键字:字符串 查找      更新时间:2023-10-16

所以,我刚刚开始这门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);