我想测试一个 std::string
是否包含任何范围的数字,例如 5 到 35
在 std::string s = "XDGHYH20YFYFFY"
是否会有函数,或者我必须将数字转换为字符串,然后使用循环来查找每个函数?
最佳答案
我可能会使用将除数字以外的所有内容都视为空白的语言环境,并从充满该语言环境的字符串流中读取数字并检查它们是否在范围内:
#include <iostream>
#include <algorithm>
#include <locale>
#include <vector>
#include <sstream>
struct digits_only: std::ctype<char>
{
digits_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc['0'], &rc['9'], std::ctype_base::digit);
return &rc[0];
}
};
bool in_range(int lower, int upper, std::string const &input) {
std::istringstream buffer(input);
buffer.imbue(std::locale(std::locale(), new digits_only()));
int n;
while (buffer>>n)
if (n < lower || upper < n)
return false;
return true;
}
int main() {
std::cout << std::boolalpha << in_range(5, 35, "XDGHYH20YFYFFY");
return 0;
}
关于c++ - 检查字符串是否包含数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3096042/