I have the following code with me that works.
#include <iostream>
#include <string>
using namespace std;
main ()
{
string s = "key1=value&key2=value2&key3=value3";
cout << "Original : "<<s.c_str () <<endl;
string s1 = "key2";
int pos;
pos = s.find (s1, 0);
string s3 (s, 0, pos+s1.size () + 1);
s3 += "newvalue";
string r_s = s;
r_s.replace (0, pos+s1.size ()+1, "");
const char* ptr = strtok (const_cast<char*>(r_s.c_str ()), "&");
string full_replace = s1;
full_replace += "=";
string ptr_s (ptr);
full_replace += ptr_s;
int loc = s.find (full_replace);
string s2 = s;
if (loc != string::npos)
s2.replace (0, loc + full_replace.size (), "");
s3 += s2;
cout << "New : "<<s3.c_str ()<<endl;
}
./a.out
Original : key1=value&key2=value2&key3=value3
New : key1=value&key2=newvalue&key3=value3
You can see the value2 is replaced with newvalue retaining the rest of the string as is.
I just have a feeling this isn't a very smart way of achieving this. Can someone suggest a better way of doing this? Efficient and faster, if possible.

New Topic/Question
Reply



MultiQuote





|