C语言实现mystrcpy等函数

 mystrcpy

#include <stdio.h>
#include <stdlib.h>
 
char *mystrcpy(char *ptr, const char *str)
{
    char *tmp = ptr; 
 
    while((*ptr++ = *str++) != '\n')
    {
        continue;
    }
    return tmp;
}
 
int main()
{
    char *str = "hello world";
    char *ptr;
    ptr = (char *)malloc(sizeof(char) * 1024);
 
    mystrcpy(ptr, str);
 
    printf("%s\n", ptr);
 
    return 0;
}

mystrcmp

#include <stdio.h>
#include <stdlib.h>
 
int mystrcmp(char *str, char *ptr)
{
    int i = 0;
    while (*(str + i) != '\0' && *(ptr + i) != '\0')
    {
         if(*str > *ptr)
        {
            return 1;
        }
        else if(*str < *ptr)
        {
            return -1;
        }
        i++;
    }
 
    if(*str != '\0')
    {
        return 1;
    }
     if(*ptr != '\0')
     {
         return -1;
     }
 
     return 0;
}
 
int main()
{
    int i;
    char *str, *ptr;
    str = (char *)malloc(sizeof(char)*64);
    ptr = (char *)malloc(sizeof(char)*64);
 
    printf("please input two strings:\n");
    scanf("%s%s", str, ptr);
 
   i = mystrcmp(str, ptr);
 
   if(i == 0)
   {
       printf("%s = %s", str, ptr);
   }
 
   if(i == 1)
   {
       printf("%s > %s", str, ptr);
   }
 
   if(i == -1)
   {
       printf("%s < %s", str, ptr);
   }
    return 0;
}

mystrlen

#include <stdio.h>
#include <stdlib.h>
 
void mystrlen(char *ptr)
{
    int i = 0;
    while(*(ptr + i) != '\0')// while(*ptr++ != '\0')
    {
        i++;
    }
    printf("%d\n", i);
 
}
 
int main()
{
    char *str;
    str = (char *)malloc(sizeof(char)* 64);
 
    printf("please input a string:\n");
    scanf("%s", str);
 
    mystrlen(str);
 
    return 0;
}

mystrcat

#include <stdio.h>
 
char *mystrcat(char *dest,const char *src)
{
	char *p;
	p = dest;
	while(*dest)
		dest++;
	while(*src)
	{
		*dest++ = *src++;
	}
 
	*dest = '\0';
 
	return p;
}
 
int main()
{	
	char str1[] = "hello";
	char str2[] = "world";
	mystrcat(str1,str2);
 
	printf("str1 = %s\n",str1);
 
	return 0;
 
}

猜你喜欢

转载自blog.csdn.net/sinat_39440759/article/details/82931219
今日推荐