如果你想从字符串中提取数字,例如从 NIC_25G_TEMP
和 NIC_100G_TEMP
中提取 25
和 100
,可以使用正则表达式或简单的字符串操作来实现。以下是两个不同的方法的示例。
方法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助手提供,问题来源于学员提问