ZBLOG

NIC_25G_TEMP、NIC_100G_TEMP获取里面的数字

如果你想从字符串中提取数字,例如从 NIC_25G_TEMPNIC_100G_TEMP 中提取 25100,可以使用正则表达式或简单的字符串操作来实现。以下是两个不同的方法的示例。

方法1:使用正则表达式

这是一个简洁的方法,适合于更复杂的情况。

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

int main() {
    std::string str1 = "NIC_25G_TEMP";
    std::string str2 = "NIC_100G_TEMP";

    // 正则表达式匹配数字
    std::regex re(R"(\d+)");

    std::smatch match;

    if (std::regex_search(str1, match, re)) {
        std::cout << "Number in " << str1 << ": " << match.str() << std::endl;
    }

    if (std::regex_search(str2, match, re)) {
        std::cout << "Number in " << str2 << ": " << match.str() << std::endl;
    }

    return 0;
}

方法2:使用字符串操作

如果只需要提取固定格式中的数字,可以手动处理字符串。

#include <iostream>
#include <string>

int extractNumber(const std::string& str) {
    size_t start = str.find('_') + 1; // 查找第一个下划线的位置并加一
    size_t end = str.find('G', start); // 找到 'G' 字符的位置

    // 提取子串并转换为整数
    return std::stoi(str.substr(start, end - start));
}

int main() {
    std::string str1 = "NIC_25G_TEMP";
    std::string str2 = "NIC_100G_TEMP";

    int num1 = extractNumber(str1);
    int num2 = extractNumber(str2);

    std::cout << "Number in " << str1 << ": " << num1 << std::endl;
    std::cout << "Number in " << str2 << ": " << num2 << std::endl;

    return 0;
}

输出结果

无论选择哪种方法,输出都会是:

Number in NIC_25G_TEMP: 25
Number in NIC_100G_TEMP: 100

这两种方法各有优缺点。如果你的输入格式比较复杂且多变,正则表达式会更加灵活。而如果知道输入格式较为固定,则字符串操作可能会更高效。根据你的需求选择合适的方法!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=7962

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?