简体   繁体   中英

c++ splitting up a string

I'm learning c++ by myself with a book and I've gotten stuck on an exercise. I'm supposed to split up a string into two parts, each part is separated by a space, and forget the rest but my code doesn't forget the rest for some reason.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main(){

string original;
string first;
string second;

bool firstDone = false;
bool secondDone = false;

int firstSpace = 0;
int secondSpace = 0;

cout << "Enter string: ";

getline(cin, original);

cout << "The original string is: " << original << endl;

for(int i = 0; i < original.length(); i++)
{
    if(original[i] == ' ' && !firstDone){
        firstSpace = i;
        firstDone = true;
    }
    else if(original[i] == ' ' && !secondDone){
        secondSpace = i;    
        secondDone = true;
    }
}

cout << "The first space is at: " << firstSpace << endl << "The second space is at: " 
     << secondSpace << endl;

first = original.substr(0, firstSpace);
second = original.substr(firstSpace + 1, secondSpace);

cout << "The first string is: " << first << endl << "The second string is: "
     << second << endl;

return 0;

}

when I run it I get

Enter string: test1 test2 test3

The original string is: test1 test2 test3

The first space is at: 5

The second space is at: 11

The first string is: test1

The second string is: test2 test3

and as you can see the second string is "test2 test3" when it should only be "test2". Can someone point out what I did wrong?

ps I'm not very far in the book and many other solutions I found online had a bunch of variables and other functions I'm not familiar with so can we limit the answers to the style I've used (if possible).

actually the substr() second parameter is the length of the string from the starting offset that you mention in first parameter. Do like following:

second = original.substr(firstSpace + 1, secondSpace-(firstSpace+1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM