You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将任意长度字符串分割为单个单词并存入vector?

解决字符串拆分到vector<string>的问题

嘿,我来帮你搞定这个字符串拆分的问题!先看看你当前代码里的几个小问题:

  • 循环条件while(choice != " ")逻辑不对,choice是整个待拆分的字符串,除非它只剩一个空格,否则这个条件要么永远不成立,要么一开始就不执行
  • 当find(" ")找不到空格时,会返回string::npos,这时候space = choice.find(" ")-1会变成一个异常的大数值,导致substr行为出错
  • substr(0, space)的第二个参数是长度,你这里用索引减1的方式计算,逻辑上有偏差,比如第一个单词到空格前的索引是space_idx,那单词长度应该是space_idx而非space_idx-1

接下来给你两种靠谱的解决方案:

方法一:用stringstream(最推荐)

C++的<sstream>库可以轻松处理字符串拆分,自动跳过空格,代码简洁又不容易出错:

#include <iostream>
#include <vector>
#include <sstream>
#include <string>

using namespace std;

int main() {
    string choice = "Hello world this is a test string";
    vector<string> broken;
    stringstream ss(choice);
    string word;
    
    // 自动按空格拆分,把每个单词存入vector
    while (ss >> word) {
        broken.push_back(word);
    }
    
    // 验证结果
    for (const auto& w : broken) {
        cout << w << endl;
    }
    return 0;
}

这个方法的优势是:不管有多少个连续空格,都会自动跳过,完全不需要手动处理索引,省心又高效。

方法二:手动处理字符串(如果你想自己实现逻辑)

如果你想手动处理空格拆分,修正后的代码逻辑如下:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    string choice = "Hello world this is a test string";
    vector<string> broken;
    size_t pos = 0;
    string word;
    
    while ((pos = choice.find(" ")) != string::npos) {
        // 提取从当前位置到空格的单词
        word = choice.substr(0, pos);
        if (!word.empty()) { // 避免连续空格导致空字符串存入
            broken.push_back(word);
        }
        // 截取空格之后的剩余字符串
        choice = choice.substr(pos + 1);
    }
    // 处理最后一个单词(如果字符串不以空格结尾)
    if (!choice.empty()) {
        broken.push_back(choice);
    }
    
    // 验证结果
    for (const auto& w : broken) {
        cout << w << endl;
    }
    return 0;
}

这里的关键点:

  • 用size_t类型存储索引(因为find返回的是size_t,避免负数问题)
  • 每次找到空格后,截取正确长度的单词(substr(0, pos),pos是空格的索引,刚好等于单词的长度)
  • 单独处理最后一个没有后续空格的单词
  • 加入空字符串判断,避免连续空格导致vector里出现空元素

内容的提问来源于stack exchange,提问作者Jonny Yi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:33:29