替換空格
題目來源:牛客網——替換空格
題目描述
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
解題思路:
從前往後遍歷記錄空格數目count;
從後往前 替換空格
代碼:
class Solution {
public:
void replaceSpace(char *str,int length) {
int count = 0; //空格數目
// 從前往後遍歷空格數目
for(int i = 0; i < length; i++){
if(str[i] == ' ')
count ++;
}
// 從後往前替換空格
for(int i = length-1; i>=0; i--){
// 如果不是空格,則後移
if(str[i] != ' ')
str[i + count*2] = str[i];
//若爲空格,則插入%20
else{
count --;
str[i + count*2] = '%';
str[i + count*2 + 1] = '2';
str[i + count*2 + 2] = '0';
}
}
}
};