split s string at the first whitespace

Dec 19, 2008 at 2:10am
Can anyone help? My program is due on Monday. I'm trying to split strings I'm reading from a file. The split function will divide the original string into two parts, putting the second part of the string into the empty parameter and leaving the first part of the string (without the space and the rest of the string) in the original variable. For example: "you have" the original string will be changed to "you" and the second string will get the value "have". Then main will call the function and print out both strings. This is my code, I'm lost with this.

//Function to split the original string at the first whitespace
void split(string &first, string &second)
{

string::size_type pos;
pos=first.find(' ',0);
second=first.substr(pos,0);

return;
}
Dec 19, 2008 at 7:39am
Hi

You are very close. you will make it.

Take a piece of paper, write "you have" and mark the position ("pos" in your code) of the ' '-character. Then, from that mark, think of what needs to go into the first string and what needs to go into the second string. Then, using substr(), put them there.
Last edited on Dec 19, 2008 at 7:39am
Dec 19, 2008 at 11:19pm
Is this correct?

string::size_type pos;
pos=first.find(' ',0);
second=first.substr(pos+1);
first=first.substr(0,pos);
Last edited on Dec 19, 2008 at 11:41pm
Dec 20, 2008 at 3:34am
That would almost work, but if there is no space in your string? .find() would return string::npos, and adding 1 to that would generate an error.
Dec 20, 2008 at 12:25pm
tyky: Yes, It would, assuming that there is a whitespace in the string. As firedraco mentions, you will probably need to check this explicitly by checking the returned value from the find()-call. But otherwise, you're good.
Dec 20, 2008 at 1:11pm
thank you for your help. My professor wanted us to include a whitespace in each string.
Topic archived. No new replies allowed.