面试题4:替换空格

题目:请实现一个函数,把字符串中的每个空格替换成”%20“。例如输入”We are happy.",则输出“We%20are%20happy."。

 1 void replaceBlank(char string[], int length)
 2 {//length为string的总容量
 3     if (string == NULL && length <= 0)
 4         return ;
 5     int oriLength = 0;
 6     int numberOfBlank = 0;
 7     int i = 0;
 8     while (string[i]!='\0')
 9     {
10         oriLength++;
11         if (string[i++]==' ')
12             numberOfBlank++;
13     }
14     /*newLength 为把空格替换成'%20'之后的长度*/
15     int newLength = oriLength + 3*numberOfBlank;
16     if (newLength > length)
17         return;
18     int indexOfOriginal = oriLength;
19     int indexOfNew = newLength;
20     while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
21     {
22         if (string[indexOfOriginal]!=' ')
23         {
24             string[indexOfNew--] = string[indexOfOriginal--];
25         }
26         else
27         {
28             indexOfOriginal--;
29             string[indexOfNew--] = '0';
30             string[indexOfNew--] = '2';
31             string[indexOfNew--] = '%';
32         }
33     }
34 }

 

posted @ 2015-06-30 16:54  Rosanne  阅读(194)  评论(0编辑  收藏  举报