C String理解—— 字符串替换函数

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 int Replace(char *sSrc, char *sMatchStr, char *sReplaceStr)
 5 {
 6         int  StringLen;
 7         char caNewString[100];
 8         char *FindPos = strstr(sSrc, sMatchStr);//strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串,如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
 9         if( (!FindPos) || (!sMatchStr) )
10                 return -1;
11         while(FindPos)
12         {
13                 memset(caNewString, 0, sizeof(caNewString));
14                 StringLen = FindPos - sSrc;
15                 
16                 strncpy(caNewString, sSrc, StringLen);//char *strncpy(char *dest, const char *src, int n),把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回dest
17                 strcat(caNewString, sReplaceStr);//将两个char类型连接。结果存在第一个参数中,返回指向第一个参数的指针。
18                 strcat(caNewString, FindPos + strlen(sMatchStr));
19                 strcpy(sSrc, caNewString);
20                 FindPos = strstr(sSrc, sMatchStr);//保证替换掉所有sMatchStr
21         }
22         return 0;
23 }
24 int main(void){
25     char* s,*s1,*s2;
26     
27     //为每个字符串分配 1K空间
28     s=(char*)malloc(1024);
29     s1=(char*)malloc(1024);
30     s2=(char*)malloc(1024);
31     if(!s || !s1 || !s2){
32         printf("内存分配失败!\n");             exit(1);        }
33     
34     //字符串赋值
35     strcpy(s,"Turn Left!Left!");
36     strcpy(s1,"Left");
37     strcpy(s2,"Right");
38 
39 // 替换字符串中特征字符串为指定字符串
40     Replace(s,s1,s2);
41     //打印    
42     printf("%s\n",s);    
43     //释放分配的堆空间
44     free(s);
45         free(s1);
46         free(s2);
47     return 0;
48 }

C小作业,通过这个深刻了解到 字符串指针只是指向字符串中的第一个字符。同时学习了strstr,strcpy,strncpy,strcat等函数的使用。


 1  int main(void){  
 2     char *a="bcd";  
 3      printf("输出字符:%c /n", *a);  
 4    printf("输出字符:%c /n", *(a+1) );  
 5      printf("输出字符串:%s /n", a); /*输出字符串,使用"%s";而且a之前不能有星号"*"  */   
 6  }  
 7  /*运行结果如下: 
 8  输出字符:b
 9 输出字符:c 
10  输出字符串:bcd*/  

 

 

 

posted on 2017-05-28 17:50  明静志远  阅读(1161)  评论(0编辑  收藏  举报