C++如何从字符串中提取出首个完整的整数数值
C++ 提取字符串中首个连续整数的实现方法
核心思路
先定位字符串中第一个数字字符的起始位置,再向后匹配到第一个非数字字符作为结束位置,截取中间的数字子串后转换为整数类型即可。
实现代码(C++11及以上,无额外依赖)
#include <iostream> #include <string> #include <stdexcept> int extractFirstInteger(const std::string& input) { // 查找第一个数字字符的位置 const size_t startPos = input.find_first_of("0123456789"); if (startPos == std::string::npos) { throw std::invalid_argument("输入字符串中不存在数字"); } // 从起始位置向后查找第一个非数字字符的位置 const size_t endPos = input.find_first_not_of("0123456789", startPos); // 截取数字子串并转换为int类型 return std::stoi(input.substr(startPos, endPos - startPos)); } int main() { const std::string testStr = "thdfwrhwh456dfhdfh764"; try { std::cout << extractFirstInteger(testStr) << std::endl; // 输出结果:456 } catch (const std::exception& e) { std::cerr << "错误:" << e.what() << std::endl; } return 0; }
注意事项
- 若需要支持提取负整数,可调整查找逻辑:判断数字前一位是否为
-符号,将起始位置向前移动一位即可 - 当提取的数字超出
int类型取值范围时,std::stoi会抛出std::out_of_range异常,可替换为std::stol(返回long)或std::stoll(返回long long)适配更长的整数范围 - 如果需要兼容C++03及更早版本,可以用
isdigit()手动遍历字符串定位起止位置,再用atoi()完成类型转换
内容的提问来源于stack exchange,提问作者jm531
相关产品推荐
相关产品推荐

