如何将此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 06:18:24
java字典的等价物是map或unordered_map
至于json问题,您需要一个库来解析json,我推荐使用excellent one from Professor Lemire (github lemire)
我刚刚为你写了一个简单的json解析器。请注意,您将需要使用c++1z进行编译,否则将收到警告:decomposition declaration only available with -std=c++1z or -std=gnu++1z
g++ -std=c++1z test.cpp && ./a.out
#include <unordered_map>
#include <iostream>
#include <sstream>
using namespace std;
void jsonDecode(unordered_map <string, char> &m, string s) {
constexpr char delimiter = '"';
for (int i = 0; i < s.size(); ) {
if (s[i++] == delimiter) {
stringstream ss;
while (s[i] != delimiter)
ss << s[i++];
string key = ss.str();
++i;
while (s[i] != delimiter) i++;
char value = s[++i];
m[key] = value;
i+=2;
}
}
}
int main(void) {
unordered_map <string, char> m;
string s = R"({"|1|":"A","|2|":"B","|3|":"D","|4|":"C"})";
jsonDecode(m, s);
string y = "|1||2||3||4|";
for (auto &[k,v] : m)
y.replace(y.find(k), k.size(), string(1, v));
cout << y << endl;
return 0;
}输出:
ABDC您可以阅读有关replace method here的文章
发布于 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
复制相似问题