string 中的 length函数 和size函数 返回值问题

时间:2023-03-08 23:18:58
string 中的 length函数 和size函数 返回值问题

string 中的 length函数 和
size函数 的返回值  (  还有 char [ ] 中 测量字符串的  strlen 函数 )

应该是 unsigned int 类型的

不可以 和 -1 比较。

应尽量避免 unsigned int 类型 和 int类型 数据 的比较 。

当unsigned
int 类型 和 int类型 数据 比较 时 ,会 把int 类型 转换 为 unsigned int类型 。如果 int是负数 ,转换 为 unsigned int 会是 一个 很大 的正整数,所以 比较的时候 会很危险。

若 将 unsigned int
强制 转换 为 int 再比较 时,不能说 没有 问题。我觉得 也可能会 出现问题,相对来说 还是 比较好的。(摘自strlen返回值的问题

-------------------------------------------------------------------------------------------------------------------------

// 例1

// string a="abcd";

// -1 和 a.length() 的比较结果

//代码

#include<iostream>
#include<string>
using namespace std;
int main()
{
string a="abcd";
cout<<"a-----"<<a<<endl;
cout<<"a.length()-----"<<a.length()<<endl;
if( -1 >= a.length() )
cout<<"*************"<<endl;
return 0;
}

输出:

a-----abcd

a.length()-----4

*************

Press any key to continue

-------------------------------------------------------------------------------------------------------------------------

// 例2

// string a="abcd";

// -1 和 a.size() 的比较结果

//代码

#include<iostream>
#include<string>
using namespace std;
int main()
{
string a="abcd";
cout<<"a----"<<a<<endl;
cout<<"a.size()----"<<a.size()<<endl;
if(-1>=a.size())
cout<<"*************"<<endl;
return 0;
}

输出:

a----abcd

a.size()----4

*************

Press any key to continue

-------------------------------------------------------------------------------------------------------------------------

// 例3

// char a[100]="abcd";

// -1 和 strlen(a) 的比较结果

//代码

#include<iostream>
#include<string>
using namespace std;
int main()
{
char a[100]="abcd";
cout<<"a----"<<a<<endl;
cout<<"strlen(a)----"<<strlen(a)<<endl;
if( -1>=strlen(a) )
cout<<"*************"<<endl;
return 0;
}

输出:

a----abcd

strlen(a)----4

*************

Press any key to continue