劍指offer--替換空格
阿新 • • 發佈:2018-12-12
題目描述
請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。
解析
這題主要看使用的語言,我使用的c++,通過本題加深了對c++字串的理解
class Solution { public: void replaceSpace(char *str,int length) { char* temp = new char[length]; strcpy(temp,""); for(int i=0;i<strlen(str);i++){ if(str[i]==' '){ strcat(temp,"%20"); } else{ char a[2] = {str[i],'\0'}; strcat(temp,a); } } strcpy(str,temp); } };