I have to work with strings that contain URL encodings like "%C3%A7", and I need to convert these sequences to the corresponding printable characters. Therefore I wrote a function. It works, but it seems rather awkward. I am an absolute C/C++ beginner. Perhaps someone can point me to a more elegant solution, please.
#include <iostream>
using namespace std;
static inline void substitute_specials(string &str) {
const struct {string from,to;} substitutions[] { { "20"," " },{ "24","$" },{ "40","@" },{ "26","&" },{ "2C","," },{ "C3%A1","á" },{ "C3%A7","ç" },{ "C3%A9","é" } };
size_t start_pos = 0;
while ((start_pos = str.find("%", start_pos)) != string::npos) {
start_pos++;
for (int i=0; i< extent < decltype(substitutions) > ::value; i++) {
if (str.compare(start_pos,substitutions[i].from.length(),substitutions[i].from) == 0) {
str.replace(start_pos-1, substitutions[i].from.length()+1, substitutions[i].to);
start_pos += substitutions[i].to.length()-1;
break;
}
}
}
}
int main() {
string testString = "This%20is %C3%A1 test %24tring %C5ith %40 lot of spe%C3%A7ial%20charact%C3%A9rs%2C %26 worth many %24%24%24";
substitute_specials(testString);
cout << testString << "\n";
return 0;
}
EDIT 26.12.2016: I am still stuck with this problem. I found some suggestions for librarys and some hand written functions, but if the run at all they will only decode %xx (2 byte hex code in string) like %20 = space. I havn't found any that would do 4 byte code like %C3%84 = Ä and I wasn't able to modify any. Also curl_easy_unescape library() asks for 2 byte codes. I found exactly what I need is available in javascript, the corresponding functions are encodeURI() / decodeURI(), see http://www.w3schools.com/tags/ref_urlencode.asp The C/C++ source of decodeURI() would probably solve my problem. Line 3829 in https://dxr.mozilla.org/mozilla-central/source/js/src/jsstr.cpp look like an implementation of that, but I can't extract what I need. From the other examples I have found: many use sscanf to convert a 2 byte hex code to an int using %x hex format, and then static_castint to retrieve the correct char. How can I modify that for 4-byte sequences? Current status of my function is
wstring url_decode2(char* SRC) {
wstring ret;
wchar_t ch;
int i, ii;
char sub[5];
for (i=0; i<strlen(SRC); i++) {
if (SRC[i]=='%') {
if ((SRC[i+3]=='%') && (SRC[i+1]>='A')) {
sub[0]=SRC[i+4];
sub[1]=SRC[i+5]; // ( also tried lsb/msb )
sub[2]=SRC[i+1]; // skip +3, it's %
sub[3]=SRC[i+2]; //
sub[4]='\0';
i=i+5;
} else {
sub[0]=SRC[i+1];
sub[1]=SRC[i+2];
sub[2]='\0';
i=i+2;
}
sscanf(&sub[0], "%x", &ii);
ch=static_cast<wchar_t>(ii);
ret+=ch;
} else
ret+=SRC[i];
}
return ret;
}
Can anyone help me, please?