例题7:字符串替换题集

1、一换多

将字符串中的空格替换为%20。如:we are family --->we%20are%20family。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <assert.h>
 4 void SwapStr(char *str)
 5 {
 6      7     int len = strlen(str);
 8     int i = 0;
 9     int j = 0;
10     int count = 0;   //计数器,用来统计空格的个数
11     for(; i < len ; i++)
12     {
13         if(str[i] ==' ')
14             count++;
15     }
16     i = len;//将i指向原来数组的最后
17     j = len + 2*count;//j指向增加后的数组的最后
18     while (i != j)
19     {
20         if(str[i] ==' ')
21         {
22             str[j--] = '0';
23             str[j--] = '2';
24             str[j--] = '%';
25             i--;
26         }
27         else 
28         {
29             str[j--] = str[i--];
30         }
31     }
32 }
33 int main()
34 {
35     char str[30] ="we are family!";
36     printf("%s ,%d\n",str,strlen(str));
37     SwapStr(str);
38     printf("%s ,%d\n",str,strlen(str));
39     return 0;
40 }

运行结果:

we are family! ,14
we%20are%20family! ,18

 

2、一对一
函数将字符串中的字符'*'移到字符串的前部分,前面的非'*'字符后移,但不能改变非'*'字符的先后顺序,函数返回串中非'*'字符的数量。

如:as**df*ghj***k*l --->*******asdfghjkl

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <assert.h>
 4 int  MoveStr(char *str)
 5 {
 6     assert(str != NULL);
 7     int len = strlen(str);
 8     int i,j;//指向非*和*
 9     int count = 0;//统计
10     //for (i = j= len-1;i>=0;)
11     //{
12     //    if(str[i] != '*')
13     //    {
14     //        char tmp;
15     //        tmp = str[j];
16     //        str[j] = str[i];
17     //        str[i] = tmp;
18     //        i--;
19     //        j--;
20     //    }
21     //    else
22     //    {
23     //        i--;
24     //        count++;
25     //    }
26     //}
27     
28     for (i = j =len - 1;j >=0;j--)
29     {
30         if(str[i]!='*')
31         {
32             i--;
33         }
34         else if(str[j] !='*')//将非*换到后面
35         {
36             str[i] = str[j];
37             str[j] = '*';
38             i--;
39         }
40     }
41     return i+1;
42 }
43 int main()
44 {
45     char str[] = "aas**fg*jk***lo";
46     printf("%s\n",str);
47     MoveStr(str);
48     printf("%s,%d\n",str,MoveStr(str));
49     return 0;
50 }

3、多对一

   将字符串中连续的空格删除,只保留一个空格
如: I     am     happy! ---> I am happy!

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <assert.h>
 4 void Change(char *str)
 5 {
 6     assert (str != NULL);
 7     int len = strlen(str);
 8     int i;
 9     int j=0;
10     for (i = 1;i<=len;i++)
11     {
12             if(str[i] == str[i+1]&&str[i+1]==' ')
13             {
14                 while (str[i]==' ')
15                 {
16                     ++i;
17                 }
18                 --i;    
19             }
20             str[++j] = str[i];
21     }
22 }
23 int main()
24 {
25     char str[]="I        am       happy  !";
26     printf("%s\n",str);
27     Change(str);
28     printf("%s\n",str);
29     return 0;
30 }

 

posted @ 2024-12-21 16:36  木鱼932  阅读(27)  评论(0)    收藏  举报