给出字符串:const auto foo = "lorem\tipsum"s
我可以通过执行以下操作找到空白的迭代器:find(cbegin(foo), cend(foo), [](const auto& i) { return isspace(i); })
但我想要位置。我有两种选择:
答案 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("")
。