实现一个函数,把字符串中的每个空格替换成”%20”

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 void replaceBlank(char *str);
 5 
 6 int main()
 7 {
 8     char str[32];
 9     gets_s(str,32);
10     replaceBlank(str);
11     puts(str);
12     system("pause");
13     return 0;
14 }
15 
16 void replaceBlank(char *str)
17 {
18     int old_length = 0;//原字符串的长度
19     int new_length = 0;//新字符串的长度
20     int blank_cnt = 0;//空格的个数
21     int i = 0;//原字符串的下标
22     int j;//新字符串的下标
23 
24     if(str[i] == '')
25     {
26         printf("The string is empty!
");
27         return;
28     }
29     //计算原字符串的长度和空格的个数
30     while(str[i] != '')
31     {
32         ++old_length;
33         if(str[i] == ' ')
34             ++blank_cnt;
35         ++i;
36     }
37 
38     new_length = old_length + 2 * blank_cnt;
39     i = old_length;
40     j = new_length;
41 
42     while(i >= 0 && j > i)
43     {
44         if(str[i] == ' ')
45         {
46             str[j--] = '0';
47             str[j--] = '2';
48             str[j--] = '%';
49         }
50         else
51             str[j--] = str[i];
52         --i;
53     }
54 }
原文地址:https://www.cnblogs.com/cpsmile/p/4776817.html