如何获取我的区域设置的空格字符串?
How Can I Get a string of My locale's Whitespaces?
给定字符串:const auto foo = "loremtipsum"s
我可以通过以下操作找到空白的迭代器:find(cbegin(foo), cend(foo), [](const auto& i) { return isspace(i); })
但我想要的位置。我有两个选择:
- 使用
distance
:distance(cbegin(foo), find(cbegin(foo), cend(foo), [](const auto& i) { return isspace(i); }))
- 查找
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("")
。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 2D数组来自文本输入,中间有空格
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 有没有办法为 TAB 字符(反斜杠 t)"t"设置特定数量的最大空格数C++?
- 如何使用put_time()设置日期格式以删除前面的空格和零
- 如何获取我的区域设置的空格字符串?
- C++如何将整个字符数组设置为空格
- 在名称包含 WinDBG 中的空格的重载函数处设置断点
- 设置带空格的字符串格式
- 如何将包含空格的字符串设置为HTML文本字段(在表单中)的默认值
- emacs c++输入缩进设置为4空格