Last active
August 29, 2015 14:02
-
-
Save xun-gong/999e81b5eb89db67c2e6 to your computer and use it in GitHub Desktop.
CareerCup1.4.cpp
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
/* Chapter 1 | |
* 1.4 Write a method to replace all the space in a string to %20 | |
* you may assume the given space is sufficient. | |
* Example: "Mr John Troy(_extra_space_)" | |
* =>"Mr%20John%20Troy." | |
*/ | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
void replace(char* str) | |
{ | |
int counter = 0; | |
for (int i = 0; i < strlen(str) - 1; ++i) | |
{ | |
if (str[i] == ' ' && str[i+1] != ' ') | |
{ | |
counter++; | |
} | |
} | |
int extend_len = strlen(str) + 2 * counter; | |
str[extend_len] = '\0'; // assign memory space | |
char* p = str + extend_len - 1; | |
for(int i = strlen(str) - 1; i >= 0; i--) | |
{ | |
if (str[i] == ' ') | |
{ | |
*p-- = '0'; | |
*p-- = '2'; | |
*p-- = '%'; | |
} | |
else | |
*p-- = str[i]; | |
} | |
} | |
// Main Function | |
int main(int argc, char const *argv[]) | |
{ | |
char str[] = "Mr John Troy."; | |
replace(str); | |
cout << str << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment