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

如何实现多分隔符字符串分割至vector并忽略指定标点?

嘿,这个问题我熟!要把字符串按空格+各种标点分割成无标点的单词,其实有几种实用的方法,我给你拆解一下:

方法1:手动遍历字符串(最直观,可控性强)

这种方法不需要依赖额外库,完全自己掌控每一步逻辑,新手也能轻松理解:

#include <vector>
#include <string>
#include <cctype>

std::vector<std::string> splitString(const std::string& s) {
    std::vector<std::string> result;
    std::string currentWord;
    
    for (char c : s) {
        // 判断当前字符是否是要忽略的标点或空格
        if (std::isspace(c) || c == ',' || c == '.' || c == '?' || c == '!' || c == ';' || c == ':') {
            // 如果已经攒了单词,就加入结果并清空临时变量
            if (!currentWord.empty()) {
                result.push_back(currentWord);
                currentWord.clear();
            }
        } else {
            // 不是分隔符,就把字符加到当前单词里
            currentWord += c;
        }
    }
    // 处理字符串末尾的最后一个单词(避免漏掉)
    if (!currentWord.empty()) {
        result.push_back(currentWord);
    }
    
    return result;
}

方法2:用正则表达式(代码更简洁)

如果你的项目用的是C++11及以上版本,用<regex>库可以一行核心代码搞定匹配,非常省心:

#include <vector>
#include <string>
#include <regex>
#include <iterator>

std::vector<std::string> splitString(const std::string& s) {
    std::vector<std::string> result;
    // 正则规则:匹配任意非标点、非空格的连续字符(至少一个)
    std::regex re(R"([^,\.\?!;: ]+)");
    // 遍历所有匹配结果,直接塞进vector
    std::copy(std::sregex_iterator(s.begin(), s.end(), re),
              std::sregex_iterator(),
              std::back_inserter(result));
    return result;
}

注:正则里的[^,\.\?!;: ]表示“排除逗号、句号、问号、感叹号、分号、冒号、空格这些字符”,+表示匹配至少一个连续的符合规则的字符

方法3:自定义ctype facet(适配stringstream场景)

要是你平时习惯用stringstream处理字符串分割,这种方法可以让>>运算符自动把标点当成空格处理,完美适配你的使用习惯:

#include <vector>
#include <string>
#include <sstream>
#include <locale>

// 自定义字符分类规则,把指定标点标记为空格分隔符
struct PunctuationAsSpace : std::ctype<char> {
    PunctuationAsSpace() : std::ctype<char>(get_table()) {}
    static const mask* get_table() {
        static std::vector<mask> table(classic_table(), classic_table() + table_size);
        // 把目标标点标记为空格类型
        table[','] = table['.'] = table['?'] = table['!'] = table[';'] = table[':'] = space;
        return table.data();
    }
};

std::vector<std::string> splitString(const std::string& s) {
    std::vector<std::string> result;
    std::stringstream ss(s);
    // 给stringstream安装自定义的字符分类规则
    ss.imbue(std::locale(ss.getloc(), new PunctuationAsSpace));
    std::string word;
    // 用>>读取,自动按空格+标点分割单词
    while (ss >> word) {
        result.push_back(word);
    }
    return result;
}

测试示例

随便拿你给的例子测试一下,比如:

#include <iostream>

int main() {
    std::string testStr = "Hello, my name is Jack!";
    auto words = splitString(testStr);
    for (const auto& word : words) {
        std::cout << word << " ";
    }
    // 输出:Hello my name is Jack
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:52:54