Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created January 27, 2014 19:04
Show Gist options
  • Save tolinwei/8655272 to your computer and use it in GitHub Desktop.
Save tolinwei/8655272 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
using namespace std;
void replace_per(string &s)
{
int space_num = 0;
for (auto it = s.begin(); it != s.end(); it++) {
if (*it == ' ') {
space_num++;
}
}
int old_size = s.size();
int new_size = s.size() + 2 * space_num;
s.resize(new_size);
auto new_end = s.end() - 1;
auto old_end = s.begin() + old_size - 1;
while (old_end != s.begin()) {
if (*old_end != ' ') {
//not space
*new_end = *old_end;
} else {
//space
*new_end = '0';
*(--new_end) = '2';
*(--new_end) = '%';
}
old_end--;
new_end--;
}
return;
}
/*
Input: "Mr John Smith"
Output: "Mr%20John%20Smith"
*/
int main(int argc, char *argv[]) {
string s = "Mr John Smith";
replace_per(s);
cout << s << endl;
return 0;
}
@gregkr
Copy link

gregkr commented Jan 27, 2014

void replace_per(string& s)
{
size_t pos ;
while ( pos = s.find(" ") != -1)
s.replace( pos, pos + 1, "%20");
return ;
}
Why no?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment