如何获取我的区域设置的空格字符串?

How Can I Get a string of My locale's Whitespaces?

本文关键字:设置 空格 字符串 区域 我的 何获取 获取      更新时间:2023-10-16

给定字符串:const auto foo = "loremtipsum"s

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

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

  1. 使用distance:distance(cbegin(foo), find(cbegin(foo), cend(foo), [](const auto& i) { return isspace(i); }))
  2. 查找isspace并构造其内容的硬编码字符串:foo.find_first_of(" fnrtv")

显然,2更简单,它将返回string::npos,我必须为其测试1,但我想请求我的区域设置为我提供一个所有空白的字符串,而不是对字符串进行编码。有没有一个函数可以用来获取这个字符串,或者一种方法来烹饪它?

这是一种半天真的方法,但我们可以使用一个函数来检查isspace()char在提供的区域设置中可以保持的所有可能值,并返回一个仅包含返回true的值的字符串。然后,您可以将该字符串与选项2一起使用。

这是N == std::numeric_limits<char>::max() - std::numeric_limits<char>::min()的O(N)操作,但如果不更改区域设置,则只需要运行一次并捕获字符串。

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("C"))替换std::locale("")