c++拆分字符串

c++ splitting up a string

本文关键字:字符串 拆分 c++      更新时间:2023-10-16

我正在通过一本书自学c++,我在一个练习中卡住了。我应该把一个字符串分成两部分,每一部分用一个空格隔开,然后忘记剩下的部分,但是我的代码由于某种原因没有忘记剩下的部分。

#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;
}

当我运行它时,我得到

输入字符串:test1 test2 test3

原字符串为:test1 test2 test3

第一个空格在:5

第二个空格在:11

第一个字符串是:test1

第二个字符串是:test2 test3

,你可以看到第二个字符串是"test2 test3",而它应该是"test2"。有人能指出我做错了什么吗?

注。我在书中并不是很远,我在网上找到的许多其他解决方案都有一堆变量和其他函数,我不熟悉,所以我们可以将答案限制在我使用的风格(如果可能的话)。

实际上,substr()第二个参数是从第一个参数中提到的开始偏移量开始的字符串长度。按如下方式做:

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