替换空格

剑指offer里,面试题4“替换空格”。作者给出了一种解法,但是觉得比较复杂:对字符串要遍历两次,而且需要在原来的字符串的基础上拼接字符串,感觉也比较麻烦。我尝试一下,遍历一次也是可以的。但是不可避免的需要申请更多的空间,时间或者空间总要消耗一个的。
       因为字符串的总长度是可以知道的,那么替换后最差的情况就是全部被替换。基于这样可以申请固定大小的空间,对内存的浪费并不会很大。需要主要的是‘’的问题。程序里忽略了对申请的空间的指针的检测,对测试用例的选择也不全面,但是这仅仅是为了说明这个问题。不要在意这些细节。:-) 
       源程序如下: 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 char* subBlank2Hex(char* src);
 6 
 7 int main(void)
 8 {
 9     char* sen = "we are happy";
10     char* ten = "  ";
11     char* uen = " a ";
12     char* osen = subBlank2Hex(sen);
13     char* oten = subBlank2Hex(ten);
14     char* ouen = subBlank2Hex(uen);
15     printf("%s
%s
%s
",osen,oten,ouen);
16 }
17 
18 char* subBlank2Hex(char* src)
19 {
20     int index = 0;
21     char* tmpsrc = src;
22     char* tmpdes = (char*)malloc(sizeof(char)*strlen(src)*3+1);
23     char* des = tmpdes;
24     while(*tmpsrc!='')
25     {
26         if(*tmpsrc==' ')
27         {
28             tmpdes[index]='%';
29             tmpdes[index+1]='2';
30             tmpdes[index+2]='0';
31             index = index + 3;
32         }
33         if(*tmpsrc!=' ')
34         {
35             tmpdes[index]=*tmpsrc;
36             index++;
37         }
38         tmpsrc++;
39     }
40     tmpdes[index]='';
41     return des;
42 }
原文地址:https://www.cnblogs.com/warnet/p/3862565.html