user14890854
user14890854

Reputation:

Parse string and replace

How i could convert this javascript code to 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)

output: ABDC

I got the "decoding key" in a std::string like:

  std::string key = "{\"|1|\":\"A\",\"|2|\":\"B\",\"|3|\":\"D\",\"|4|\":\"C\"}";

Based on the properties of this key do a string replace in my_string.

Example:

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| to A, |2| to B ... etc comes from the std::string key

Then my_string now is ABDC.

Do i need to convert the std:: string key to another data type? I mean something similar to an object like on javascript, im not familiar with c++.

Upvotes: 1

Views: 339

Answers (2)

Antonin GAVREL
Antonin GAVREL

Reputation: 11219

Equivalents of java dictionnary is map or unordered_map

As for your json question, you need a library to parse json, I recommend the excellent one from Professor Lemire (github lemire)

I just wrote you a simple json parser for you. Note that you will need to compile with c++1z or you will get the warning: 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;
}

output:

ABDC

You can read about replace method here

Upvotes: 1

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

Here is a direct "translation" to 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;
}

Upvotes: 0

Related Questions