C++字符串分割

3

我正在通过一本书自学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”。有人能指出我做错了什么吗?
P.S. 我在书中的进度不是很远,我在网上找到的其他解决方案都有许多变量和其他我不熟悉的函数,所以如果可能的话,请限制答案的风格。
1个回答

2

实际上,substr()函数的第二个参数是从你在第一个参数中指定的起始偏移量开始的字符串长度。可以按照以下方式进行操作:

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

哦,第二个参数是长度而不仅仅是结束点?现在这样就更有意义了,非常感谢。 - Jc.kal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接