strlen, strcpy, strcmp函数的实现

时间:2022-05-22 15:49:02

在Bjarne Stroustrup(C++创始人,他的主页)所写的《The C++ Programming Language, special edition》书中的第6章6.6节的第10题练习题中,要求实现strlen, strcpy, strcmp三个函数,2011年11月份我已发过两篇文章来实现此三个函数(字符串处理函数的实现strcmp函数的实现),以前的实现代码中,为了避免命名冲突,更改了相关函数的名称(如strlen改为strLen),本文采用命名空间来避免名称的冲突,且代码风格更加紧凑:

/*
the C++ programming language, special edition. ch6.6-5 P140

10. (*2) Write these functions:s strlen(), which returns the length of a C-style string; stcpy(),
which copies a string into another; and stcmp(), which compares two strings. Consider what
the argument types and return types ought to be. Then compare your functions with the standard library
versions as declared in<cstring>(<string.h>) and as specified in 20.4.1.
*/
#include <iostream>

using namespace std;

namespace MJN {
size_t strlen(const char *str);
char *strcpy(char *dst, const char *src);
int strcmp(const char *str1, const char *str2);
}

//test
int main() {
cout << MJN::strlen("hello, world") << endl; //output: 12
cout << MJN::strlen("") << endl; //output: 0
//cout << MJN::strlen(0) << endl; //error, and no exception throw.

char dst[100];
char *src = "hello, world";
MJN::strcpy(dst, src);
cout << dst << endl; //output: hello, world
cout << MJN::strlen(dst) << endl; //output: 12

char *str1 = "hello";
char *str2 = "helle";
cout << MJN::strcmp(str1, str2) << endl; //output: 10
cout << strcmp(str1, str2) << endl; //output: 1
str1 = 0;
cout << MJN::strcmp(str1, str2) << endl; //a negative number
//cout << strcmp(str1, str2) << endl; //error

return 0;
}

size_t MJN::strlen(const char *str) {
if (!str) cerr << "MJN::strlen error: pointer to string is 0\n";
size_t len = 0;
while (*str++) ++len;
return len;
}

char * MJN::strcpy(char *dst, const char *src) {
if (!dst || !src) {
return dst;
}
char *dst_origin = dst;
while (*dst++ = *src++);
return dst_origin;
}

int MJN::strcmp(const char *str1, const char *str2) {
if (!str1 || !str2) {
return str1 - str2;
}
while (*str1 && *str2 && *str1 == *str2) {
++str1;
++str2;
}
return *str1 - *str2;
}


当函数参数中的字符串指针为0时,函数应该向外抛出异常(在main函数中捕获),而不是正确地返回或在函数中处理异常,在后续的版本中将会添加抛出异常的功能。

References:

The C++ Programming Language, special edition. ch6.2.5 P125

http://www.cplusplus.com/strlen

http://www.cplusplus.com/strcpy

http://www.cplusplus.com/strcmp