我正在通过一本书自学 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;
}
当我运行它时,我得到了
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
正如您所见,第二个字符串是“test2 test3”,而它应该只是“test2”。有人可以指出我做错了什么吗?
附注我在书中的内容并不多,我在网上找到的许多其他解决方案都有一堆我不熟悉的变量和其他函数,所以我们可以将答案限制在我使用过的风格(如果可能的话)。
最佳答案
实际上 substr() 第二个参数是从您在第一个参数中提到的起始偏移量开始的字符串长度。喜欢以下内容:
second = original.substr(firstSpace + 1, secondSpace-(firstSpace+1));
关于c++拆分一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32674866/