剑指offer面试题4

 1 #include<iostream>
 2 using namespace std;
 3 
 4 void replace(char ch[]) {
 5     int count = 0;
 6     int len = 0;
 7     char *p = ch;
 8     while(*p != '\0') {
 9         if(*p == ' ')
10             count++;
11         p++;
12         len++;
13     }
14     char *n = new char[len+count*2+1];
15     strcpy(n, ch);
16     char *p1 = n + len;
17     char *p2 = n + len+count*2;
18     while( p1 >= n && p1 < p2) {
19         if(*p1 == ' ') {
20             *p2-- = '0';
21             *p2-- = '2';
22             *p2-- = '%';
23         } 
24         else {
25             *p2 = *p1;
26             p2--;
27         }
28         p1--;
29     }
30     cout << n << endl;
31 }
32 
33 int main()
34 {
35     char ch[] = "We are happy.";
36     replace(ch);
37     return 0;
38 }

 

posted @ 2014-06-05 09:02  soul390  阅读(167)  评论(0编辑  收藏  举报