# Space Replacement

## Question

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.

Example
Given "Mr John Smith", length = 13.

The string after replacement should be "Mr%20John%20Smith".

Note
If you are using Java or Python，please use characters array instead of string.

Challenge
Do it in-place.


## 題解

### Java

public class Solution {
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
public int replaceBlank(char[] string, int length) {
if (string == null) return 0;

int space = 0;
for (char c : string) {
if (c == ' ') space++;
}

int r = length + 2 * space - 1;
for (int i = length - 1; i >= 0; i--) {
if (string[i] != ' ') {
string[r] = string[i];
r--;
} else {
string[r--] = '0';
string[r--] = '2';
string[r--] = '%';
}
}

return length + 2 * space;
}
}

class Solution {
public:
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
int replaceBlank(char string[], int length) {
int space = 0;
for (int i = 0; i < length; i++) {
if (string[i] == ' ') space++;
}

int r = length + 2 * space - 1;
for (int i = length - 1; i >= 0; i--) {
if (string[i] != ' ') {
string[r] = string[i];
r--;
} else {
string[r--] = '0';
string[r--] = '2';
string[r--] = '%';
}
}

return length + 2 * space;
}
};