1. Description
Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
2. Example
Given "Mr John Smith", length = 13.
The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17.
3. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C++" active="active"]
int replaceBlank(char string[], int length) { if (string == NULL) { return 0; } int spaceCount = 0; for (int i = 0; i < length; i++) { if (string[i] == ' ') { spaceCount++; } } int len = length + (spaceCount << 1); int right = len - 1; for (int i = length - 1; i >= 0; i--) { if (string[i] != ' ') { string[right--] = string[i]; } else { string[right--] = '0'; string[right--] = '2'; string[right--] = '%'; } } return len; }
[/restab]
[/restabs]
4.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C++" active="active" ]
#includeusing namespace std; class LintCode0212 { public: int replaceBlank(char string[], int length) { if (string == NULL) { return 0; } int spaceCount = 0; for (int i = 0; i < length; i++) { if (string[i] == ' ') { spaceCount++; } } int len = length + (spaceCount << 1); int right = len - 1; for (int i = length - 1; i >= 0; i--) { if (string[i] != ' ') { string[right--] = string[i]; } else { string[right--] = '0'; string[right--] = '2'; string[right--] = '%'; } } return len; } }; int main() { LintCode0212 lintcode; char string[] = { 'M', 'r', ' ', 'J', 'o', 'h', 'n', ' ', 'S', 'm', 'i', 't', 'h', '\0' }; printf("%d", lintcode.replaceBlank(string, 13)); return 0; }
[/restab]
[/restabs]
Comments | NOTHING