How do I get a part of the a string in C++?

前端 未结 5 2145
醉梦人生
醉梦人生 2020-12-11 03:40

How do I get a part of a string in C++? I want to know what are the elements from 0 to i.

5条回答
  •  星月不相逢
    2020-12-11 03:46

    You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/

    // string::substr
    #include 
    #include 
    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;
    }
    

提交回复
热议问题