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. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)
EXAMPLE
Input: “Mr John Smith ”
Output: “Mr%20John%20Smith”
#include <iostream> #include <cstring> // for strlen, but in Xcode, it's not necessary to include this using namespace std; void replaceSpaces(char originalStr[]) { int spaceCount = 0; int newLength = 0; int length = (int)strlen(originalStr); for(int i=0;i<length;i++) { if(originalStr[i] == ' ') spaceCount++; } newLength = length + spaceCount * 2; //not * 3 because original space has been counted once originalStr[newLength] = '\0'; //string terminate for(int i = length -1;i>=0;i--) { if(originalStr[i] == ' ') { originalStr[newLength - 1] = '0'; originalStr[newLength - 2] = '2'; originalStr[newLength - 3] = '%'; newLength-=3; } else { originalStr[newLength - 1] = originalStr[i]; newLength--; } } } int main(int argc, const char * argv[]) { char ch[] = "Mr John Smith"; replaceSpaces(ch); cout<<ch<<endl; return 0; }
char operation:
So, the value of ch cannot be modified!
If you would like to modify the value of ch, then
Consider the length of a char array,
strlen(ch) doesn't count the null character (\0)
Thus,
It's better to resize the char array size.