Created
January 27, 2014 19:04
-
-
Save tolinwei/8655272 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
void replace_per(string& s)
{
size_t pos ;
while ( pos = s.find(" ") != -1)
s.replace( pos, pos + 1, "%20");
return ;
}
Why no?