剑指offer 04_替换字符串中的空格

 #include <stdio.h>

 void ReplaceBlank(char string[],int length){
if(string == NULL || length == 0){
return;
} int originalLength = 0;//
int blankCount = 0; while(string[originalLength] != '\0'){
if(string[originalLength] == ' '){
++blankCount;
}
++originalLength;
} int newLength = originalLength + blankCount * 2; if(newLength > length){//not enough space
return;
} int indexFirst = originalLength;
int indexSecond = newLength;
while(indexFirst>=0 && indexSecond>indexFirst){
if(string[indexFirst] == ' '){
string[indexSecond--] = '0';
string[indexSecond--] = '2';
string[indexSecond--] = '%';
}else{
string[indexSecond--] = string[indexFirst];
}
--indexFirst;
}
} int main(){
char str[50] = "We are happy.";
printf("str = %s\n",str); ReplaceBlank(str,50);
printf("str = %s\n\n",str); char str1[50] = "Wearehappy.";
printf("str1 = %s\n",str1); ReplaceBlank(str1,50);
printf("str1 = %s\n\n",str1); char str2[50] = " We are happy.";
printf("str2 = %s\n",str2); ReplaceBlank(str2,50);
printf("str2 = %s\n\n",str2); char str3[50] = "";
printf("str3 = %s\n",str3); ReplaceBlank(str3,50);
printf("str3 = %s\n\n",str3); return 0;
}

结果

str = We are happy.
str = We%20are%20happy. str1 = Wearehappy.
str1 = Wearehappy. str2 = We are happy.
str2 = %%%20We%20are%20happy. str3 =
str3 =
上一篇:libpcap 库使用(二)


下一篇:POJ 3751 JAVA