Breaking a string down

I have a string line containing a full name i.e. "John E Baker"

I want to break it down into smaller strings: FirstName, LastName and MiddleInitial.

I need to write a function that will do this. However this fucntion needs to be versatile becasue it will recieve the line string several time and each time it will be different.

So for instance when the first lien is processed the main program will loop and a new string will be read into the function i.e. "Michael B Burns"

How can I write the fucntion code to break down any string line into three substrings firstname lastname and middle initial?
You could use a stringstream.

1
2
3
4
5
string line = "John E Baker";
istringstream ss(line);

string a, b, c;
ss >> a >> b >> c;


Of course, middle initial is optional, so this code could require some tweaking if there is just "firstname lastname".
Last edited on
In all honesty, using the sstream is the best way to do this, but another less effient way is to try something like this:

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>

using namespace std;

void breakName(string,string[]);

int main(){
    string name = "John E Baker";
    string fullName[3];

    breakName(name,fullName);

    for (int x = 0; x < 3; x++)
        cout << fullName[x]<<endl;

}

void breakName(string name,string splitName[]){
    int spacePos,lastSpace = 0;
        for (int x = 0; x < 3; x++){
            lastSpace = name.find(" ",spacePos) + 1;
            spacePos = name.find(" ",lastSpace);
            splitName[x] = name.substr(lastSpace,spacePos-lastSpace);
        }
}


Topic archived. No new replies allowed.