strlen, strcpy, strcmp函数的实现

在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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值