gpt4 book ai didi

c++ - 我怎样才能得到一串我的语言环境的空格?

转载 作者:行者123 更新时间:2023-11-30 05:29:40 34 4
gpt4 key购买 nike

给定字符串:const auto foo = "lorem\tipsum"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("\f\n\r\t\v")

显然 2 更简单,它会返回 string::npos 我必须测试 1 ,但我想请求我的语言环境为我提供所有空格的字符串,而不是对字符串进行硬编码。有没有我可以用来获取这个字符串的函数,或者有什么方法可以处理它?<​​/p>

最佳答案

这是一种半天真的方法,但我们可以有一个函数来检查 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("")使用不同的语言环境,例如 std::locale("C")如果您不想使用当前语言环境。

关于c++ - 我怎样才能得到一串我的语言环境的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309670/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com