small_potato small_potato - 6 months ago 28
C++ Question

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

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


You want to use std::string::substr. Here's an example, shamelessly copied from

// 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;