small_potato small_potato - 3 years ago 132
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download