c ++ 11是否提供与python maketrans / translate中实现的类似解决方案?

时间:2014-12-22 09:40:57

标签: c++ python-2.7 c++11 transliteration

c ++ 11是否提供了在python maketrans/translate中实现的优雅解决方案?

from string import maketrans 

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);

2 个答案:

答案 0 :(得分:5)

因为我知道没有内置功能,但你可以想象实现一个:

#include <functional>
#include <string>
#include <unordered_map>

std::function<std::string(std::string)>
maketrans(const std::string& from, const std::string& to) {
    std::unordered_map<char, char> map;
    for (std::string::size_type i = 0;
         i != std::min(from.size(), to.size()); ++i) {
        map[from[i]] = to[i];
    }
    return [=](std::string s) {
        for (auto& c : s) {
            const auto mapped_c = map.find(c);
            if (mapped_c != map.end()) {
                c = mapped_c->second;
            }
        }
        return s;
    };
}

#include <iostream>
int main() {
    const std::string intab = "aeiou";
    const std::string outtab = "12345";
    const auto translate = maketrans(intab, outtab);

    const std::string str = "this is string example....wow!!!";
    std::cout << translate(str) << std::endl;
    return 0;
}

答案 1 :(得分:1)

我的尝试。需要帮助从两个字符串创建地图:

#include <iostream>
#include <string>
#include <map>
using namespace std;

using TransMap = std::map<char, char>;
void translate(std::string& string, TransMap map ){
    for(auto& c : string){
        const auto itr = map.find(c);
        if(itr != map.end()) c = itr->second;
    }
}

int main() {
    std::string test = "123456789";
    TransMap map{ {'1', 'a'}, {'2', 'b'}, {'3', 'c'}, {'4', 'd'}, {'5', 'e'} };
    translate(test, map);
    std::cout << test << '\n';
    return 0;
}