您的位置:首页 > 其它

使用4种方法来算字符串长度

2009-04-02 05:16 288 查看
str::strlen,

string::length,

loop操作,

形式语言的标准递归。

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;

int strlen_by_loop( char* const psz )
{
char* p = psz;
int iLen = 0;

while( *p++ ) iLen++;

return iLen;
}//

int strlen_by_recusive( char* const psz )
{
if( *psz == '/0' )
return 0;
else
return strlen_by_recusive( psz + 1 ) + 1;
}//

int main()
{
char* psz = "hello,world";
string str( psz );

cout<<"Length of 'hello,world' by 'std::strlen()' = "<<strlen( psz )<<endl
<<"Length of 'hello,world' by 'string::length()' = "<<str.length()<<endl
<<"Length of 'hello,world' by 'strlen_by_loop' = "<<strlen_by_loop( psz )<<endl
<<"Length of 'hello,world' by 'strlen_by_recusive' = "<<strlen_by_recusive( psz )<<endl<<endl;

return 0;
}//
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐