剑指Offer02 替换空格

 1 /*************************************************************************
 2     > File Name: 02_Replace_Blank.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年08月24日 星期三 01时28分33秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 
10 void ReplaceBlank(char* str)
11 {
12     if (str==NULL)
13     {
14         return;
15     }
16     
17     int blankCount = 0;
18     int alphaCount = 0;
19     int i = 0;
20     while (str[i] != '\0')
21     {
22         if (str[i] == ' ')
23             blankCount ++;
24         alphaCount ++;
25         
26         i ++;
27     }
28     printf("alphaCount is %d\n", alphaCount);
29     printf("blankCount is %d\n", blankCount);
30     
31     int newLength = alphaCount + 2*blankCount;
32     printf("newLength is %d\n", newLength);
33     int p1 = alphaCount + 1;
34     int p2 = newLength + 1;
35     while (p1>=0 && p2>p1)
36     {
37         if (str[p1] == ' ')
38         {
39             str[p2--] = '0';
40             str[p2--] = '2';
41             str[p2--] = '%';
42         }
43         else
44         {
45             str[p2--] = str[p1];
46         }
47         p1 --;
48     }
49 }
50 
51 int main()
52 {
53     char str[] = "We are Happy!";
54     printf("Before: %s\n", str);
55     ReplaceBlank(str);
56     printf("After: %s\n", str);
57 }

 

posted @ 2016-08-24 02:50  Juntaran  阅读(196)  评论(0编辑  收藏  举报