检查字符串是否包含数字范围

检查字符串是否包含数字范围

本文介绍了检查字符串是否包含数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个 std :: string 用于包含任何范围的数字,例如 5到35 std :: string s =XDGHYH20YFYFFY会有函数还是我必须将一个数字转换为字符串,然后使用循环来找到每一个? p>

I'd like to test a std::string for containing numbers of any range e.g 5 to 35 in a std::string s = "XDGHYH20YFYFFY" would there be function or I would have to convert a number to string and then use a loop to find each one?

推荐答案

我可能会使用一个除了数字之外的所有空格作为空格的区域,并从字符串流中读取数字locale,并检查它们是否在范围内:

I'd probably use a locale that treated everything except digits as white-space, and read the numbers from a stringstream imbued with that locale and check if they're in range:

#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;
}

这篇关于检查字符串是否包含数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 03:06