CCI_Q1.5

本文参考该作者文章:

作者:Hawstein
出处:http://hawstein.com/posts/ctci-solutions-contents.html

一.Q:写一个函数,把字符串中所有的空格替换为%20 。

思路:

int *replace1(char[],int):首先计算字符串中的空格的数量,新字符串的长度应该是多2cnt数量的长度(每个空格替换为%20需要增加2个字符,x个空格增加2x个字符)。申请一个额外数组,将原数组复制到新数组即可。

replace2(char[],int):如果原数组长度够大,可以从后向前将字符串复制到原数组中。

CODE:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 char * replace1(char a[],int l)
 5 {
 6     int i,j=0,cnt=0;
 7     for(i=0;i<l;i++)
 8     {
 9         if(a[i]==' ')
10             cnt++;
11     }
12     char *t=malloc((l+2*cnt+1)*sizeof(char));
13     for(i=0;i<l;i++)
14     {
15         if(a[i]==' ')
16         {
17             t[j++]='%';
18             t[j++]='2';
19             t[j++]='0';
20         }
21         else
22             t[j++]=a[i];
23     }
24     t[j]='';
25     return t;
26 }
27 void replace2(char a[],int l)
28 {
29     int i,j=0,cnt=0;
30     for(i=0;i<l;i++)
31         if(a[i]==' ')
32             cnt++;
33     for(i=l-1,j=l+2*cnt,a[j--]='';i>=0;i--)
34     {
35         if(a[i]==' ')
36         {
37             a[j--]='0';
38             a[j--]='2';
39             a[j--]='%';
40         }
41         else
42             a[j--]=a[i];
43     }
44 }
45 int main()
46 {
47     char a[100]="i am tong ";
48     char *t=replace1(a,strlen(a));
49     printf("%s
",t);
50     replace2(a,strlen(a));
51     printf("%s
",a);
52     return 0;
53 }
原文地址:https://www.cnblogs.com/jhooon/p/3572847.html