strlen函数、strcpy函数、strncpy函数、strcat函数、strcmp函数的举例用法
#include <stdio.h>
#include <string.h>
int my_strlen(const char *str)
{
int count = 0;
while(*str)
{
count++;
str++;
}
return count;
}
char *my_strcpy(char *dst,const char *src)
{
char *tmp = dst;
while(*src)
{
*dst = *src;
src++;
dst++;
}
*dst = '\0';
dst = tmp;
return dst;
}
char *my_strncpy(char *dst,const char *src,int nbytes)
{
char *tmp = dst;
while(*src && nbytes)
{
*dst = *src;
src++;
dst++;
nbytes--;
}
*dst = '\0';
dst = tmp;
return dst;
}
char *my_strcat(char *dst,const char *src)
{
char *tmp = dst;
if(dst == NULL || src == NULL)
{
return NULL;
}
while(*dst)
{
dst++;
}
while(*src)
{
*dst = *src;
dst++;
src++;
}
*dst = '\0';
dst = tmp;
return dst;
}
int my_strcmp(const char *src,const char *dst)
{
while(*src == *dst)
{
if(*src == '\0')
{
return 0;
}
src++;
dst++;
}
return 1;
}
int main()
{
char str[1000];
char src_str[1000];
char dest_str[1000];
char *p;
int cmd = 0;
int str_len = 0;
int nbytes = 0;
int ret;
while(1)
{
printf("=================show the func=================\n");
printf("1.calc the str len\n");
printf("2.copy the src_str to dest_str\n");
printf("3.copy the src_str n bytes to dest_str\n");
printf("4.link the src_str to dest_str\n");
printf("5.compare the str1 and str2\n");
printf("please input your cmd\n");
printf("===============================================\n");
scanf("%d",&cmd);
switch(cmd)
{
case 1:
printf("input your str\n");
scanf("%s",str);
printf("str = %s\n",str);
str_len = my_strlen(str);
printf("str_len = %d\n",str_len);
printf("strlen(str) = %d\n",strlen(str));
break;
case 2:
printf("input your src str\n");
scanf("%s",src_str);
printf("src str is %s\n",src_str);
p = my_strcpy(dest_str,src_str);
my_strcpy(dest_str,src_str);
printf("dest_str = %s\n",p);
break;
case 3:
printf("input your src str\n");
scanf("%s",src_str);
printf("input the bytes you want to copy\n");
scanf("%d",&nbytes);
printf("you want copy %d bytes %s to dest \n",nbytes,src_str);
my_strncpy(dest_str,src_str,nbytes);
printf("dest str %s copy %d bytes from src \n",dest_str,nbytes);
break;
case 4:
printf("input your src str\n");
scanf("%s",src_str);
printf("input your dst str\n");
scanf("%s",dest_str);
printf("src str is %s,dst str is %s\n",src_str,dest_str);
my_strcat(dest_str,src_str);
printf("dst str is %s\n",dest_str);
break;
case 5:
printf("please input the s1 str\n");
scanf("%s",src_str);
printf("please input the s2 str\n");
scanf("%s",dest_str);
printf("s1 is %s,s2 is %s\n",src_str,dest_str);
ret = my_strcmp(src_str,dest_str);
printf("ret = %d\n",ret);
default :
printf("your cmd is not support,please input again\n");
break;
}
}