使用区域设置查找字符串中的子字符串

Find substring in string using locale

本文关键字:字符串 查找 区域 设置      更新时间:2023-10-16

我需要根据当前语言环境的规则查找字符串是否包含子字符串。

因此,如果我正在搜索字符串"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";
}

但是,如您所见...这不会做你想要的。请参阅您问题中的评论。