剑指offer 04_替换字符串中的空格
1 #include <stdio.h> 2 3 void ReplaceBlank(char string[],int length){ 4 if(string == NULL || length == 0){ 5 return; 6 } 7 8 int originalLength = 0;// 9 int blankCount = 0; 10 11 while(string[originalLength] != '\0'){ 12 if(string[originalLength] == ' '){ 13 ++blankCount; 14 } 15 ++originalLength; 16 } 17 18 int newLength = originalLength + blankCount * 2; 19 20 if(newLength > length){//not enough space 21 return; 22 } 23 24 int indexFirst = originalLength; 25 int indexSecond = newLength; 26 while(indexFirst>=0 && indexSecond>indexFirst){ 27 if(string[indexFirst] == ' '){ 28 string[indexSecond--] = '0'; 29 string[indexSecond--] = '2'; 30 string[indexSecond--] = '%'; 31 }else{ 32 string[indexSecond--] = string[indexFirst]; 33 } 34 --indexFirst; 35 } 36 } 37 38 39 int main(){ 40 char str[50] = "We are happy."; 41 printf("str = %s\n",str); 42 43 ReplaceBlank(str,50); 44 printf("str = %s\n\n",str); 45 46 47 char str1[50] = "Wearehappy."; 48 printf("str1 = %s\n",str1); 49 50 ReplaceBlank(str1,50); 51 printf("str1 = %s\n\n",str1); 52 53 54 char str2[50] = " We are happy."; 55 printf("str2 = %s\n",str2); 56 57 ReplaceBlank(str2,50); 58 printf("str2 = %s\n\n",str2); 59 60 61 char str3[50] = ""; 62 printf("str3 = %s\n",str3); 63 64 ReplaceBlank(str3,50); 65 printf("str3 = %s\n\n",str3); 66 67 68 return 0; 69 }
结果
str = We are happy. str = We%20are%20happy. str1 = Wearehappy. str1 = Wearehappy. str2 = We are happy. str2 = %20%20%20We%20are%20happy. str3 = str3 =