看到很多面试都会要求你写一些简单的字符串操作函数,这些函数看起来挺简单的,但是自己写的时候就会发现不少的问题。所以我自己把大部分的字符串操作函数都写了一遍,然后用了个测试程序来测试自己写的函数与库函数是否相同。包括字符串长度函数、不受限制的字符串函数、受限制的字符串函数、字符串查找基础函数。下面直接上代码:
my_string.h 字符串操作函数头文件
#include
#define NUL '\0'
#ifndef _MY_STRING_H_H
#define _MY_STRING_H_H
//字符串长度
size_t my_strlen(char const *dst);
//不受限制的字符串函数
char *my_strcpy(char *dst, char const *src);
char *my_strcat(char *dst, char const *src);
int my_strcmp(char const *dst, char const *src);
//受限制的字符串函数
char *my_strncpy(char *dst, char const *src, size_t len);
char *my_strncat(char *dst, char const *src, size_t len);
int my_strncmp(char const *dst, char const *src, size_t len);
//字符串查找基础
char *my_strchr(char const *str, int ch);
char *my_strpbrk(char const *str, char const *group);
char *my_strstr(char const *s1, char const *s2);
char *my_strrchr(char const *str, int ch);
char *my_strrpbrk(char const *str, char const *group);
char *my_strrstr(char const *s1, char const *s2);
#endifmy_string.cpp
字符串操作函数源文件
#include "my_string.h"
//字符串长度
size_t my_strlen(char const *dst)
{
size_t length = 0;
while (*dst++ != NUL)
length++;
return length;
}
//不受限制的字符串函数
char *my_strcpy(char *dst, char const *src)
{
char *p = dst;
while (*src != NUL)
*dst++ = *src++;
*dst = NUL;
return p;
}
char *my_strcat(char *dst, char const *src)
{
char *p = dst;
while (*dst++ != NUL);
dst--;
while (*src != NUL)
*dst++ = *src++;
*dst = NUL;
return p;
}
int my_strcmp(char const *dst, char const *src)
{
while (*dst != NUL