Skip to content

Instantly share code, notes, and snippets.

@frank4565
Created February 12, 2014 04:15
Show Gist options
  • Save frank4565/8949979 to your computer and use it in GitHub Desktop.
Save frank4565/8949979 to your computer and use it in GitHub Desktop.
1.4 Write a method to replace all spaces in a string with '%20'. Youmay 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. (Note: if implementing in Java, please usea character array so that you can perform this operation inplace.)
#include<iostream>
using namespace std;
void replace(char *s, unsigned l)
{
if (s == nullptr) return;
unsigned sp = 0;
for (int i = 0; i < l; i++)
if (s[i] == ' ')
sp++;
unsigned nl = l + 2*sp;
s[nl] = '\0';
for (int i = nl-1, j = l-1; j >= 0;) {
if (s[j] != ' ')
s[i--] = s[j--];
else {
s[i--] = '0';
s[i--] = '2';
s[i--] = '%';
j--;
}
}
}
int main(int argc, char *argv[])
{
char s[100] = " Mr John Smith ";
replace(s, 14);
cout << s << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment