【劍指Offer】替換空格

題目:請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
void replaceSpace(char *str,int length) {
		char *ch=(char *)malloc(sizeof(char)*length);
        strcpy(ch,str);
        int index=0;
        int i=0;
        while(ch[i]){
            if(ch[i]==' '){
                str[index++]='%';
                str[index++]='2';
                str[index++]='0';
            }else{
                str[index++]=ch[i];
            }
            i++;
        }
        str[index]='\0';
	}
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cassert>
//方法2
void replaceSpace(char* str){
	if (str == NULL)
		return;
	int spaceNum = 0;
	char* pstr = str;
	while (*pstr != '\0'){
		if (*pstr == ' ')
			spaceNum++;
		pstr++;
	}
	int len = strlen(str);
	for (int i = len; i >= 0; i--){
		if (str[i] == ' '){
			str[i + 2 * spaceNum] = '0';
			str[i + 2 * spaceNum-1] = '2';
			str[i + 2 * spaceNum-2] = '%';
			spaceNum--;
		}
		else{
			str[i + 2 * spaceNum] = str[i];
		}
	}
}

int main(){
	char str[] = "how are you";
	replaceSpace(str);
	std::cout << str << std::endl;
	std::cin.get();
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章