Copying a segment of a string into another string.

Lets say I have a string with someone's whole name in it, and i wanted to extract each name into seperate strings. For example, "John William Dubois" into three strings: "John", "William", and "Dubois". What functions would I use? I assume I would use a for loop to search for the spaces, and use the location of the spaces to tell a functionthe begining and end of each new string, but I don't know what function(s) I would use to extract that part of a string into a new string. Well, thanks for any and all help!!! :-)
Thanks McLeano. Here is my code now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string name="John William Dubois";
  string newname[5];
  int i, n, x, pos; 
  
  n=0;
  x=0;
  for (i=0;i<name.length(); i++)
  {
      if (name[i]==' ')
      {
                     newname[n]=name.substr(x, (i-x));
                     x=i+1;
                     cout << newname[n] << endl;
                     n++;
      }
  }
  newname[n]=name.substr(x, (i-x));
  cout << newname[n] << endl;  
  cout << endl << "Press [ENTER] to continue.";
  cin.ignore(256, '\n');
  return (0);
}


It does work. But with me being a n00b I am sure there is a way to improve the code. Any suggestions?
Also look up string::find, which will help you find the spaces without having to write your own
loop to do it.
Topic archived. No new replies allowed.