Find substring in string using locale

筅森魡賤 提交于 2019-12-24 02:30:10

问题


I need to find if a string contains a substring, but according to the current locale's rules.

So, if I'm searching for the string "aba", with the Spanish locale, "cabalgar", "rábano" and "gabán" would all three contain it.

I know I can compare strings with locale information (collate), but is there any built-in or starightforward way to do the same with find, or do I have to write my own?

I'm fine using std::string (up to TR1) or MFC's CString


回答1:


For reference, here is an implementation using boost locale compiled with ICU backend:

#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 (\0) 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"
}

Output:

true
true
true
true
false



回答2:


You could loop over the string indices, and compare a substring with the string you want to find with std::strcoll.




回答3:


I haven't used this before, but std::strxfrm looks to be what you could use:

  • 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), '\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";
}

However, as you can see... This doesn't do what you want. See the comment at your question.



来源:https://stackoverflow.com/questions/19022000/find-substring-in-string-using-locale

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!