如何将此javascript代码转换为c++
key = {"|1|":"A","|2|":"B","|4|":"C","|3|":"D"}
y = "|1||2||3||4|"
for (i in key)
y = y.replace(i,key[i])
console.log(y)输出:ABDC
我在std::string中得到了“解码密钥”,如下所示:
std::string key = "{\"|1|\":\"A\",\"|2|\":\"B\",\"|3|\":\"D\",\"|4|\":\"C\"}";根据这个键的属性,在my_string中替换一个字符串。
示例:
std::string key = "{\"|1|\":\"A\",\"|2|\":\"B\",\"|3|\":\"D\",\"|4|\":\"C\"}";
std::string my_string = "|1||2||3||4|";
// . . .Replace in my_string |1| to A,|2| to B,|3| to D,|4| to C
|1|到A,|2|到B ...etc来自std::string key
那么现在的my_string就是ABDC了。
是否需要将std:: string key转换为另一种数据类型?我的意思是类似于对象的东西,比如在javascript上,我不熟悉c++。
发布于 2021-02-27 07:56:00
下面是对C++的直接“翻译”:
#include<iostream>
#include<string>
#include<unordered_map>
int main()
{
std::unordered_map<std::string, std::string> dictionary = { {"|1|","A"} , {"|2|", "B"}, {"|4|", "C"}, {"|3|", "D"} };
std::string y = "|1||2||3||4|";
size_t pos;
for (auto& a : dictionary) {
while((pos = y.find(a.first)) != std::string::npos)
y.replace(pos, a.first.length(), a.second);
}
std::cout << y << std::endl;
return 0;
}https://stackoverflow.com/questions/66393205
复制相似问题