my_strcpy,my_strncpy,my_strcmp,my_strncmp,my_strrev,my_memset的实现,亲手测试可用
/**
str.c
函数的具体实现
*/
#include "str.h"
#include <assert.h>
#include <stdio.h>
char * my_strcpy(char *dest, const char *src)
{
assert(dest != NULL && src != NULL);
char *aa = dest;
while((*aa++ = *src++) != '\0')
{}
return dest;
}
char *my_strncpy(char *dest, const char *src, int len)
{
assert(dest != NULL && src != NULL && len >= 0);
char *aa = dest;
printf("%s:len = %d\n", __FUNCTION__, len);
while(len-- > 0)
{
*aa++ = *src++;
}
return dest;
}
int my_strcmp(const char *str1, const char *str2)
{
while((*str1++ == *str2++) != '\0')
{
if(*str1 == '\0' && *str2 == '\0')
{
return 1;
}
}
return 0;
}
int my_strncmp(const char *str1,const char *str2, int len)
{
printf("%s:len = %d\n", __FUNCTION__, len);
while(len-- > 0)
{
if(*str1++ == *str2++)
continue;
else
return 0;
}
return 1;
}
char *my_strrev(char *dest, const char *src)
{
if(src == NULL)
return NULL;
char *to = dest;
char *fr = src;
while(*fr != '\0'){fr++;}
while(fr != src)
{
*to++ = *--fr;
}
return dest;
}
void *my_memset(void *src, char set, int len)
{
if(src == NULL)
return NULL;
char *aa = (char *)src;
while(len-- > 0)
{
*aa++ = set;
}
return src;
}
主函数所在文件
/**
main.c
*/
#include <stdio.h>
#include "str.h"
int main(int argc, char const *argv[])
{
char str[] = "hello world !";
printf("str>> %s\n", str);
char to1[32];
my_strcpy(to1, str);
printf("to1>> %s\n", to1);
char to2[32];
my_strncpy(to2, str, 5);
printf("to2>> %s\n", to2);
if(my_strcmp(to1, to2))
printf("to1 == to2\n");
else
printf("to1 != to2\n");
if(my_strncmp(to1, to2, 5))
printf("to1 == to2\n");
else
printf("to1 != to2\n");
char rev[32];
my_strrev(rev, str);
printf("%s >> %s\n", str, rev);
my_memset(rev, '0', 3);
printf("rev>> %s\n", rev);
return 0;
}
头文件
/**
str.h
*/
#ifndef __STR_H__
#define __STR_H__
char *my_strcpy(char *dest, const char *src);
char *my_strncpy(char *dest, const char *src, int len);
int my_strcmp(const char *str1, const char *str2);
int my_strncmp(const char *str1,const char *str2, int len);
char *my_strrev(char *dest, const char *src);
void *my_memset(void *src, char set, int len);
#endif
#Makefile文件
obj=main.o str.o
all:$(obj)
gcc -o main $(obj) -L ./
%.o:%.c
gcc -c $^ -o $@ -L ./
.PYTHON:clean
clean:
rm -rf $(obj) main
运行结果:
samba@ubuntu64:~/share/c/str$ ./main
str>> hello world !
to1>> hello world !
my_strncpy:len = 5
to2>> hello
to1 != to2
my_strncmp:len = 5
to1 == to2
hello world ! >> ! dlrow olleh
rev>> 000lrow olleh
samba@ubuntu64:~/share/c/str$