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

如何从字母数字混合字符串提取连续整数存入vector?

提取字母数字混合字符串中的连续整数并存入vector

问题分析

你的现有代码只是将所有数字字符单独提取拆分,没有识别连续的数字段,因此无法得到完整的连续整数。要解决问题,核心是识别连续的数字字符段,将每个完整的数字段转换为整数后存入vector。

基础解决方案:手动遍历实现

直接遍历字符串,用临时字符串累积连续数字字符,遇到非数字字符时,若临时字符串不为空则转成整数存入vector并清空;遍历结束后还要处理末尾可能遗留的数字段。

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

int main() {
    std::string f = "e385p336J434Y26C2Z6X5Z2";
    std::vector<int> number;
    std::string current_num;

    for (char c : f) {
        if (std::isdigit(c)) {
            current_num += c;
        } else {
            if (!current_num.empty()) {
                number.push_back(std::stoi(current_num));
                current_num.clear();
            }
        }
    }

    // 处理字符串末尾的数字段
    if (!current_num.empty()) {
        number.push_back(std::stoi(current_num));
    }

    // 验证输出
    std::cout << "number = {";
    for (size_t i = 0; i < number.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << number[i];
    }
    std::cout << "}" << std::endl;

    return 0;
}

代码说明

  • 用std::isdigit()判断字符是否为数字,比手动判断'0' <= c <= '9'更简洁可读。
  • 范围for循环遍历字符串,代码更简洁直观。
  • 每次遇到非数字字符时,检查临时字符串是否有内容,有则转换为整数存入vector并清空。
  • 遍历结束后必须检查临时字符串,避免遗漏最后一段数字。

进阶方案:正则表达式实现(C++11及以上)

如果编译器支持C++11或更高版本,可以用正则表达式快速匹配所有连续数字段:

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

int main() {
    std::string f = "e385p336J434Y26C2Z6X5Z2";
    std::vector<int> number;
    std::regex num_regex("\\d+"); // 匹配一个或多个数字的正则模式

    std::sregex_iterator it(f.begin(), f.end(), num_regex);
    std::sregex_iterator end;

    for (; it != end; ++it) {
        number.push_back(std::stoi(it->str()));
    }

    // 验证输出
    std::cout << "number = {";
    for (size_t i = 0; i < number.size(); ++i) {
        if (i > 0) std::cout << ", ";
        std::cout << number[i];
    }
    std::cout << "}" << std::endl;

    return 0;
}

代码说明

  • \\d+是正则表达式语法,表示匹配一个或多个连续数字。
  • std::sregex_iterator用于遍历字符串中所有匹配的数字子串,每个匹配结果通过it->str()获取对应的数字字符串,再转换为整数存入vector。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:15:34