Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Created June 23, 2014 20:54
Show Gist options
  • Save ivycheung1208/b0e0b2525e5e84bd347a to your computer and use it in GitHub Desktop.
Save ivycheung1208/b0e0b2525e5e84bd347a to your computer and use it in GitHub Desktop.
CC150 1.4
/* CC150 1.4
* Write a method to replace all spaces in a string with'%20'.
* You may assume that the string has sufficient space at the end of the string to hold the additional characters,
* and that you are given the "true" length of the string.
*/
#include <iostream>
#include <cstring>
using namespace std;
void replace(char *str) {
int spaceCount = 0;
for (char *begin = str, *end = begin + strlen(str);
begin != end; ++begin) {
if (*begin == ' ') // count the number of spaces
++spaceCount;
}
//cout << spaceCount << endl;
size_t newLength = strlen(str) + 2 * spaceCount; // length of replaced string
//cout << newLength << endl;
*(str + newLength) = '\0'; // null terminates the new string, assume sufficient space
char *oldStr = str + strlen(str), *newStr = str + newLength; // point at null character
while (oldStr != newStr) { // always point one past the current character, would never go past the begining
if (*(--oldStr) != ' ') // direct copy if not space
*(--newStr) = *oldStr;
else { // replace with %20 if hits space
*(--newStr) = '0';
*(--newStr) = '2';
*(--newStr) = '%';
}
}
return;
}
int main()
{
char s1[50] = " Hello World! "; // normal string with leading and tailing spaces
char s2[10] = " "; // string with all spaces
printf("%s\n", s1);
printf("%s\n", s2);
//cout << strlen(s1) << endl;
replace(s1);
printf("%s\n", s1);
replace(s2);
printf("%s\n", s2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment