把字符串中的空格替换成%20

时间:2022-10-28 08:55:15
 1 #include<iostream>
 2 using namespace std;
 3 
 4 void ChangeSpace(char* buf,int len)
 5 {
 6     if(buf == NULL || len <= 0) return ;
 7     
 8     int count = 0;
 9     for(int i=0;i<len;i++)
10     {
11         if(buf[i] == ' ')
12             count ++;
13     }
14 
15     for(int i=len-1;i>=0;i--)
16     {
17         if(buf[i] != ' ')
18             buf[i+2*count] = buf[i];
19         else 
20         {
21             count --;
22             buf[i+2*count] = '%';
23             buf[i+2*count+1] = '2';
24             buf[i+2*count+2] = '0';
25         }
26     }
27 
28     return ;
29 }
30 
31 int main()
32 {
33     char buf[64] = {0};
34     strcpy(buf,"We Are Happy");
35     ChangeSpace(buf,sizeof(buf));
36     for(int i=0;i<sizeof(buf);i++)
37     {
38         cout << buf[i];
39     }
40 
41     system("pause");
42     return 0;
43 }