如何在C++中获取字符串的一部分?

sma*_*ato 8 c++

如何在C++中获取字符串的一部分?我想知道从0到i的元素是什么.

Wil*_*ill 15

你想用std::string::substr.这是一个例子,从http://www.cplusplus.com/reference/string/string/substr/无耻地复制

// string::substr
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str="We think in generalities, but we live in details.";
                             // quoting Alfred N. Whitehead
  string str2, str3;
  size_t pos;

  str2 = str.substr (12,12); // "generalities"

  pos = str.find("live");    // position of "live" in str
  str3 = str.substr (pos);   // get from "live" to the end

  cout << str2 << ' ' << str3 << endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)