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

标签 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);

最佳答案

据我所知,没有内置函数,但你可以想象实现一个:

#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;
}

关于c++ - c++11 是否提供与 python maketrans/translate 中实现的类似的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27600042/

相关文章:

c++ - 将函数中的排序数字写入文本文件?

C++0x : when a temporary object equals another temporary object

python - 从 Python 类中提取数据

c++ - 'int [0]' c++ 的初始化程序太多

c++ - 为什么右值引用参数与重载决策中的 const 引用匹配?

c++ - 库链接器传播 : is libA->libB->App the same as libA->App<-libB

c++ - 如何删除 setpixel 放在窗口上的内容? (c++)

python - 如何乘以列表列表的位置

python - 对日期序列进行排序的最 pythonic 方法是什么?

c++ - 类型转换 NULL 的现有返回可以安全地与较新的 nullptr 进行比较吗?