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

如何验证C++字符串中'-'后仅包含数字?

解决方案:验证字符串中'-'后仅含数字

方法一:定位分隔符后逐个校验

先确认分隔符'-'的位置是否符合预期(比如固定在第4位,对应前缀"imsi"),再遍历'-'之后的所有字符,检查是否都是数字。

#include <string>
#include <cctype>

bool validateIMSI(const std::string& str) {
    size_t dashPos = str.find('-');
    // 检查分隔符位置是否正确
    if (dashPos != 4) {
        return false;
    }
    // 遍历分隔符后的每个字符,验证是否为数字
    for (size_t i = dashPos + 1; i < str.size(); ++i) {
        if (!std::isdigit(static_cast<unsigned char>(str[i]))) {
            return false;
        }
    }
    return true;
}

方法二:正则表达式匹配(C++11及以上)

用正则表达式直接匹配整个字符串格式,要求前缀为"imsi-",后续全是数字。

#include <string>
#include <regex>

bool validateIMSI(const std::string& str) {
    std::regex pattern(R"(^imsi-\d+$)");
    return std::regex_match(str, pattern);
}

^imsi-\d+$的含义:^匹配字符串开头,imsi-是固定前缀,\d+表示一个或多个数字,$匹配字符串结尾,确保整个字符串完全符合格式要求。

方法三:精准使用find_first_not_of

你之前的逻辑错误在于校验方向不对,应该直接检查'-'之后是否存在非数字字符,而非检查非字母字符。

#include <string>

bool validateIMSI(const std::string& str) {
    size_t dashPos = str.find('-');
    if (dashPos != 4) {
        return false;
    }
    // 从分隔符下一位开始查找第一个非数字字符,找不到则说明全是数字
    return str.find_first_not_of("0123456789", dashPos + 1) == std::string::npos;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:18:25