您的位置:首页 > 其它

比较两string对象字符串的大小和其长度的比较

2015-10-27 10:50 323 查看
一:比较字符串的大小

定义:在C++中定义了几种用于比较字符串的运算符,用于逐一比较string对象中的字符,并且有大小写敏感。并且定义了两字符串比较的规则:两字符串从第一个字符开始比较,如果前n个都相同,则第n+1个大的字符串比较大;也就是说并不是短的字符串就一定小,下面的例子可以很好的说明。

string line1,line2,line3;

line1="Hello";

line2="Hello,world";

line3="Hi";

则line1<line2<line3;

则对于两字符串的比较的简单程序如下:

#include<iostream>

#include<string>

using namespace std;

int main()

{

string line1,line2;

cin>>line1>>line2; //输入两字符串

if(line1==line2)

cout<<"The two strings are equal"<<endl; //相等输出

else

cout<<"The max string is "<<((line1>line2)?line1:line2);//输出较大的字符串

return 0;

}

二:比较字符串长度

字符串长度的比较就是比较string对象中字符的个数,c++中有size函数来计算一个字符串的长度,因而可以得到如下简单的程序来比较两字符串的长度.

#include<iostream>

#include<string>

using namespace std;

int main()

{

string line1,line2;

int a=0,b=0;

cin>>line1>>line2;

a=line1.size();

b=line2.size();

if(a==b)

cout<<"The length of two strings are equal"

<<" and the length is:"<<a<<endl;

else

cout<<"The large string is:"<<((a>b)?a:b);

return 0;

}

谢谢!


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: