題目描述
請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
我們先觀察我們的功能函數,void replaceSpace(char *str, int length);
這個函數中,沒有返回值,就意味着我們的一級指針既是輸入,也是輸出。
然而,我們的數據肯定是str所指向的內存,一級指針做參數時,我們無法修改 (實參) 地址,讓它指向其他的內存。
所以,我們必須要在str所指向的字符串上進行拷貝工作。
我們的字符串類似 “we are happy” 目標字符串“we%20are%20happy”
如果我們從前往後拷貝,那麼就會修改到原來的數據而無法進行完整的空格與“%20”的替換。
那麼我們只能由後往前。
解決方案:
1. 統計空格的個數
2. 計算由後往前的開始位置 字符串長度 + 空格個數 * (替換字符串-原字符串)
3. 由後往前挨個填寫對應的數據
class Solution {
public:
int countSpace(char * str, int length){
int count = 0;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
{
count++;
}
}
return count;
}
void replaceSpace(char *str, int length) {
int count = 0;
count = countSpace(str, length);
int index = length + count*2-1;
for (int i = length-1; i >=0 ; i--)
{
if (str[i] != ' ')
{
str[index--] = str[i];
}
else{
str[index--] = '0';
str[index--] = '2';
str[index--] = '%';
}
}
}
};