//问题描述: 自己编程实现类似标准库中的strlen函数
//备注:
//作者: 杨明哲
//完成日期: 200-03-25
//BUG报告; dearymz@163.com
#include <iostream>
using namespace std;
namespace ymz//名字空间的使用,防止和标准库的函数冲突
{
//字符串长度统计函数
// 得到以零结尾字符串的长度(不包括结尾字符)
size_t strlen(const char* string)
{
if(string == NULL)//对空字符串的处理
return 0;
size_t t = 0;
while(string[t] != '\0')
++t;
return t;
}
}
//注意这里常量的使用
const int bufSize = 64;//一般将缓冲的大小设置为2的指数大小
//测试函数
void main()
{
char *str = new char[bufSize + 1];//分配缓冲空间
cout<<"请输入一个字符串(回车结束):"<<endl;
cin.getline(str, bufSize);//读取要分析的字符串
cout<<"读入的字符串为:" << str<<endl;//回显一次,让用户有点(:
int strLen = static_cast<int>(ymz::strlen(str));//统计字符串的长度
cout<<"该字符串的长度为:" << strLen<<endl;
delete []str;//请注意这里不要写成 delete str.(为什么?)
cin.get();//回车退出
}
评论