使用区域设置查找字符串中的子字符串
Find substring in string using locale
我需要根据当前语言环境的规则查找字符串是否包含子字符串。
因此,如果我正在搜索字符串"aba",使用西班牙语区域设置,"cabalgar","rábano"和"gabán"这三个都将包含它。
我知道我可以将字符串与区域设置信息进行比较(整理),但是是否有任何内置或坚定的方法可以对 find 执行相同的操作,或者我必须编写自己的字符串?
我可以使用 std::string(最多 TR1)或 MFC 的 CString
作为参考,下面是使用ICU后端编译的boost语言环境的实现:
#include <iostream>
#include <boost/locale.hpp>
namespace bl = boost::locale;
std::locale usedLocale;
std::string normalize(const std::string& input)
{
const bl::collator<char>& collator = std::use_facet<bl::collator<char> >(usedLocale);
return collator.transform(bl::collator_base::primary, input);
}
bool contain(const std::string& op1, const std::string& op2){
std::string normOp2 = normalize(op2);
//Gotcha!! collator.transform() is returning an accessible null byte ( ) at
//the end of the string. Thats why we search till 'normOp2.length()-1'
return normalize(op1).find( normOp2.c_str(), 0, normOp2.length()-1 ) != std::string::npos;
}
int main()
{
bl::generator generator;
usedLocale = generator(""); //use default system locale
std::cout << std::boolalpha
<< contain("cabalgar", "aba") << "n"
<< contain("rábano", "aba") << "n"
<< contain("gabán", "aba") << "n"
<< contain("gabán", "Âbã") << "n"
<< contain("gabán", "aba.") << "n"
}
输出:
true
true
true
true
false
您可以遍历字符串索引,并将子字符串与要查找的字符串进行比较 std::strcoll
.
我以前没有用过这个,但std::strxfrm
看起来是你可以使用的:
- http://en.cppreference.com/w/cpp/locale/collate/transform
#include <iostream>
#include <iomanip>
#include <cstring>
std::string xfrm(std::string const& input)
{
std::string result(1+std::strxfrm(nullptr, input.c_str(), 0), ' ');
std::strxfrm(&result[0], input.c_str(), result.size());
return result;
}
int main()
{
using namespace std;
setlocale(LC_ALL, "es_ES.UTF-8");
const string aba = "aba";
const string rabano = "rábano";
cout << "Without xfrm: " << aba << " in " << rabano << " == " <<
boolalpha << (string::npos != rabano.find(aba)) << "n";
cout << "Using xfrm: " << aba << " in " << rabano << " == " <<
boolalpha << (string::npos != xfrm(rabano).find(xfrm(aba))) << "n";
}
但是,如您所见...这不会做你想要的。请参阅您问题中的评论。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 按类型与字符串查找对象
- 使用C RTTI(内置)通过字符串查找功能指针
- 关于获取行和字符串查找函数的问题
- 字符串查找方法找不到第一字母
- C++ 字符串.查找()
- 遇到字符串::查找的问题
- 将一个数组作为子字符串查找到另一个数组中
- 字符串查找第一个非的 C++ 问题
- 如何将通配符与字符串::查找一起使用
- 字符串::查找问题 (C++)
- 性能标准::strstr vs. 标准::字符串::查找
- C++字符串::查找崩溃应用程序
- 使用字符串查找单词的正确方法是什么
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- 使用C++根据行中的第一个字符串查找行(仅一个)
- Borland字符串::查找bug
- std::map如何通过字符串查找元素
- 字符串查找函数返回奇数
- 如何使用子字符串查找数字行的正确部分