Substrings

Hi in the example from the website it shows you have to go from "live" to the end of the string. I was wondering how you would go from the beginning of the string to "live" or even from "live" to the beginning of the string. Thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 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;
}
just use the code thats already there
1
2
3
4
size_t pos = str.find("live");
string str3 = str.substr(pos);
cout << str3 
       << endl;


as for going from live to the beginning, im not sure if this can be done without reordering the string.
great thanks for your help... so you can't go from "we" to "live" without mentioning we or the position of "we"? is there a way to tell it to go -5 characters from "live" to "live"?
Last edited on
yes, you would need to know the position of "we" and you could then go to live. as for your second question, what do you mean? you cant go backwards, but you could read from pos - 5 and then reverse the string.
Topic archived. No new replies allowed.