c++拆分字符串
c++ splitting up a string
我正在通过一本书自学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));
相关文章:
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 将字符串拆分为等长 c++ 的部分
- 如何使用 Boost C++ 打印第 n 个字符串拆分?
- 我在将字符串拆分为向量时遇到困难
- C++ 如何将字符串拆分为单个字符
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 将字符串拆分为单个单词并将它们放置在向量中
- 基于其中的数字子字符串拆分字符串
- 如何在C++中将数字字符串拆分为数组
- 如何在 c++ 中将字符串拆分为字符串 2d 数组数组
- 如何将标准::字符串拆分为标准::string_views的范围 (v3)
- 将特定格式的字符串拆分为浮点数和字符串
- 在 c++ 中将字符串拆分为单独的变量
- 用C 中的4个字符将字符串拆分
- 如何用Arduino中的另一个字符串将字符串拆分
- 如何在 Main 方法之外将字符串拆分为标记
- C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中
- 将字符串拆分为矢量 C++
- 试图将字符串拆分为两个整数