替换空格-请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

 1 class Solution {
 2 public:
 3     void replaceSpace(char *str,int length) {
 4         char *tmp;
 5         int count=0;
 6         int i;
 7         for(i=0;i<length;i++){
 8             if(*(str+i)==' ')
 9                 count++;
10         }
11         int add=sizeof("%20")-sizeof(' ');
12         add=add*count;
13         tmp=(char *)malloc(length+add);
14         int k=0;
15         for(i=0;i<length;i++){
16             if(*(str+i)==' '){
17                 *(tmp+(k++))='%';
18                 *(tmp+(k++))='2';
19                 *(tmp+(k++))='0';
20             }
21             else{
22                 *(tmp+(k++))=*(str+i);
23             }
24         }
25         for(i=0;i<=k;i++){
26             *(str+i)=*(tmp+i);
27         }
28 
29     }
30 };

 

posted @ 2015-08-24 23:43  鸭子船长  阅读(421)  评论(0编辑  收藏  举报