如何获取一系列我的区域设置的空白?

时间:2016-03-30 13:01:43

标签: c++ string locale whitespace c-strings

给出字符串:const auto foo = "lorem\tipsum"s

我可以通过执行以下操作找到空白的迭代器:find(cbegin(foo), cend(foo), [](const auto& i) { return isspace(i); })

但我想要位置。我有两种选择:

  1. 使用distancedistance(cbegin(foo), find(cbegin(foo), cend(foo), [](const auto& i) { return isspace(i); }))
  2. 查找isspace并构建一个包含其内容的硬编码字符串:foo.find_first_of(" \f\n\r\t\v")
  3. 显然 2 更简单,它将返回string::npos我必须测试 1 ,但我想请求我的语言环境为我提供了所有空格的字符串,而不是对字符串进行编码。有没有我可以用来获取这个字符串的函数,或者一种烹饪方法?

1 个答案:

答案 0 :(得分:1)

这是一种半天真的方法,但是我们可以使用一个函数来检查isspace()char可以使用提供的语言环境保存的所有可能值,并返回仅包含返回{的值的字符串{1}}。您可以将该字符串与选项2一起使用。

这是true的O(N)操作,但是如果你不改变语言环境,那么你只需要运行一次并捕获字符串。

N == std::numeric_limits<char>::max() - std::numeric_limits<char>::min()

一起使用
std::string whitespace_string(const std::locale& loc)
{
    std::string whitespace;
    for (char ch = std::numeric_limits<char>::min(); ch < std::numeric_limits<char>::max(); ch++)
        if (std::isspace(ch, loc))
            whitespace += ch;
    // to avoid infinte loop check char max outside the for loop.
    if (std::isspace(std::numeric_limits<char>::max(), std::locale(loc)))
        whitespace += std::numeric_limits<char>::max();
    return whitespace;
}

现在为您提供一个字符串,其中包含当前语言环境中的所有空格字符。如果您不想使用当前区域设置,则可以使用std::string whitespace = whitespace_string(std::locale("")); 之类的其他区域设置替换std::locale("")