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

std::vector<string>空格处理:保留双空格为独立元素的需求

解决方案:提取单词与双空格到std::vector

原代码依赖std::istream_iterator会忽略所有空白字符(单/双空格均被视为分隔符),无法区分单双空格的差异。要实现需求,需要手动遍历字符串,逐个字符处理以区分单空格和双空格,同时收集独立单词。

实现思路

  • 遍历字符串的每个字符,维护两个状态:当前正在收集的单词、连续空格的计数
  • 遇到非空格字符时:先处理之前的连续空格(双空格则作为独立元素存入vector,单空格直接忽略),再将字符加入当前单词
  • 遇到空格时:先将已收集的单词存入vector(如果存在),再增加连续空格计数
  • 遍历结束后,处理剩余的未存入单词和末尾的双空格

代码实现

#include <vector>
#include <string>

std::vector<std::string> splitWordsAndDoubleSpaces(const std::string& input) {
    std::vector<std::string> result;
    std::string currentWord;
    int spaceCount = 0;

    for (char c : input) {
        if (c != ' ') {
            // 处理之前积累的空格
            if (spaceCount > 0) {
                if (spaceCount >= 2) {
                    result.push_back("  ");
                }
                spaceCount = 0;
            }
            currentWord += c;
        } else {
            // 遇到空格,先存入当前已收集的单词
            if (!currentWord.empty()) {
                result.push_back(currentWord);
                currentWord.clear();
            }
            spaceCount++;
        }
    }

    // 处理遍历结束后剩余的单词
    if (!currentWord.empty()) {
        result.push_back(currentWord);
    }
    // 处理字符串末尾的双空格
    if (spaceCount >= 2) {
        result.push_back("  ");
    }

    return result;
}

效果验证

针对示例字符串 "this is a test string jump fox string",处理后std::vector的元素依次为:
"this", "is", "a", "test", "string", "jump", " ", "fox", "string"
完全符合需求:单词独立存储,双空格作为单独元素,单空格被剔除,所有元素无末尾空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:35:19