Change all accented letters to normal letters in C++

后端 未结 7 1091
迷失自我
迷失自我 2021-02-13 10:18

The question

How can you change all accented letters to normal letters in C++ (or in C)?

By that, I mean something like eéèêaàäâçc would become

7条回答
  •  暖寄归人
    2021-02-13 10:58

    Assuming the values are just chars, I'd create an array with the desired target values and then just replace each character with the corresponding member in the array:

    char replacement[256];
    int n(0);
    std::generate_n(replacement, 256, [=]() mutable -> unsigned char { return n++; });
    replacement[static_cast('é')] = 'e';
    // ...
    std::transform(s.begin(), s.end(), s.begin(),
                   [&](unsigned char c){ return replacement[c]; });
    

    Since the question is also tagged with C: when using C you'd need to create suitable loops to do the same operations but conceptually it would just same way. Similarily, if you can't use C++ 2011, you'd just use suitable function objects instead of the lambda functions.

    Obviously, the replacement array can be set up just once and using a smarter approach than what is outlined above. However, the principle should work. If you need to replace Unicode characters thing become a bit more interesting, though: For one, the array would be fairly large and in addition the character may need multiple words to be changed.

提交回复
热议问题