为了更好地理解string的各个库函数,现将几个常用的库函数用自己的方式实现如下:
#include<iostream>
using namespace std;
#include<cassert>
//求字符串的长度 (注:' '的长度不计算在内)
int my_strlen(char* str)
{
if (str == NULL)
{
return 0;
}
int len = 0;
while (*str++ != ' ')// ' '不计算在内
{
len++;
}
return len;
}
//string比较函数
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 != NULL && str2 != NULL);
if (*str1 == ' ' && *str2 == ' ')
return 0;
int result = 0;//记录比较结果:相等记录0;str1大于str2,记录1;str1小于str2,记录-1;
while (*str1 != ' ')
{
if ((result = *str1 - *str2) != 0) // *str1!=*str2
{
break;
}
str1++;
str2++;
}
if (result > 0)
result = 1;
else if (result < 0)
result = -1;
return result;
}
//查找str2是否为str1的字串,并返回str2在str1中第一次出现的位置
const char* my_strstr(const char* str1, const char* str2)
{
assert(str1 != NULL);
assert(str2 != NULL);
const char* ps1 = str1;
const char* ps2 = str2;
while (*ps1 != ' ')
{
const char* ret = NULL;
if (*ps1 == *ps2)
{
ret = ps1;
while (*ps1++ == *ps2++)
{
if (*ps2 == ' ')
{
return ret;
}
}
}
else
ps1++;
}
return NULL;
}
//字符串拷贝函数
char* my_strcpy(char* dst, const char* src)
{
assert(dst != NULL);
assert(src != NULL);
char* pDst = dst; //保护参数
const char* pSrc = src; //保护参数
while (*pDst != ' ')
{
*pDst++ = *pSrc++;
}
return dst;
}
//string 连接函数
char* my_strcat(char* dst, const char* src)
{
assert(src != NULL && dst != NULL);
char* pDst = dst;
const char* pSrc = src;
while (*pDst != ' ')
{
pDst++;
}
while (*pSrc != ' ')
{
*pDst++ = *pSrc++;
}
*pDst = ' ';
return dst;
}
int main()
{
char c1[10] = "abcd";
char c2[10] = "98712345";
char c3[5] = "1234";
char c4[5] = "abcd";
char c5[5] = "abbb";
char c6[5] = "abcd";
cout << "my_strlen(src):" << my_strlen(c1) << endl;
cout << "my_strcmp(c4, c5):" << my_strcmp(c4, c5) << endl;
cout << "my_strcmp(c4, c6):" << my_strcmp(c4, c6) << endl;
cout << "my_strcmp(c5, c6):" << my_strcmp(c5, c6) << endl;
const char* ret = my_strstr(c2, c3);
cout << "my_strstr(c2, c3)=> ret:" << ret << endl;
my_strcpy(c2, c3);
cout << "my_strcpy(c2, c3)=> c3:" << c3 << endl;
cout << "my_strcpy(c2, c3)=> c2:" << c2 << endl;
my_strcat(c1, c3);
cout << "my_strcat(c1, c3)=> c1:" << c1 << endl;
}