替换空格

请实现一个函数,把字符串中的每个空格替换成“%20”,例如:we are family——》we%20are%20family.

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 int main()
 5 {
 6     string str;
 7     getline(cin, str);
 8     int len = str.size();
 9     int count = 0;
10     for (int i = 0; i < len; i++)
11     {
12         if (str[i] == ' ')
13             count++;
14     }
15     count = count * 2;
16     str.append(count, '');
17     int j = len + count-1;
18     for (int i = len - 1; i >= 0; i--)
19     {
20         if (str[i] == ' ')
21         {
22             str[j] = '0';
23             str[j - 1] = '2';
24             str[j - 2] = '%';
25             j = j - 3;
26         }
27         else
28         {
29             str[j] = str[i];
30             j--;
31         }
32     }
33     cout << str << endl;
34     system("pause");
35     return 0;
36 }
原文地址:https://www.cnblogs.com/wujufengyun/p/7358391.html