1、编程实现strcpy()函数的功能

(1)方法一:

#include<stdio.h>intmain(void){charstr1[80]="abcdefg";charstr2[80];inti;for(i=0;str1[i];i++){str2[i]=str1[i];}str2[i]=0;printf("%s\n",str1);printf("%s\n",str2);return0;}

(2)、方法二:一行核心代码实现字符串复制

#include<stdio.h>intstr_copy(char*str1,char*str2);intstr_copy(char*str1,char*str2){/*for(;*str1;str1++,str2++){*str2=*str1;}*str2=0;}for(;*str1;){*str2++=*str1++;}*str2=0;while((*str2=*str1)!=0){str1++;//此时,就不用出循环在赋指为0;str2++;}while((*str2++=*str1++)!=0);*/if(str1==NULL||str2==NULL){return-1;}while(*str2++=*str1++);return0;intmain(void){charstr1[80]="abcdefg";charstr2[80];//char*str2=NULL;intret=0;ret=str_copy(str1,str2);if(ret!=0){printf("有一个地址为空,所以有错\n");}else{printf("%s\n",str1);printf("%s\n",str2);}return0;}

运行结果:


2、求子串出现在字符串中的次数

代码如下:

#include<stdio.h>#include<string.h>voidstrstrCount(char*p,char*q,int*count);voidstrstrCount(char*p,char*q,int*count){intc=0;if(p==NULL||q==NULL){printf("有地址为空,不能查找子串个数\n");return;}while(p=strstr(p,q)){c++;p=p+strlen(q);if(p==NULL){break;}}*count=c;}intmain(void){char*p="abc12421abc34345abc325423abc";char*q="abc";intcount=0;strstrCount(p,q,&count);printf("%d\n",count);return0;}

运行结果:


3、去掉字符串的前后空格

代码如下:

#include<stdio.h>#include<string.h>#include<malloc.h>voidtrimSpace(char**str1,char*str2);voidtrimSpace(char**str1,char*str2){intlength=strlen(str2);char*tmp;*str1=(char*)malloc(sizeof(char)*length);tmp=*str1;for(;*str2;str2++){if(*str2!=''){*tmp++=*str2;}}*tmp=0;}intmain(void){charstr[]="abcdefg";char*str1;printf("%s\n",str);trimSpace(&str1,str);printf("%s\n",str1);}

运行结果: