c++拆分一个字符串

标签 c++ 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;

}

当我运行它时,我得到了

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/

相关文章:

python - 一种在 Python 中连接字符串中的字符列表的优雅方法

c++ - 删除类中的自身对象

c++ - 未获得 N-Queens 问题的预期输出

c# - 同时拥有 SonarQube 的 C++ 和 c# 插件会导致 SQL Server 出错

java - 如何用Java中的参数替换所有出现的子字符串?

sql - 如何将单个列值拆分为多个列值?

c++ - 为什么 gcc 和 clang 允许我构造一个抽象类?

c++ - 在 C++ 中有条件地从 1..n 或 n..1 迭代

javascript - 似乎无法 trim 所有前导空格 - JavaScript 或 jQuery

python - 我可以将逻辑运算符 "or"与字符串结合使用吗?