比较两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;
}
谢谢!
定义:在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;
}
谢谢!
相关文章推荐
- cloudera manager和cdh目录空间报警解决
- Android最流行的网络框架
- NYOJ5 Binary String Matching
- CocoaPods的使用
- UserScoreSignService 代码记录
- 重力加速度陀螺仪传感器MPU-6050(一)
- 安卓中关于图片的类型
- Window 通过cmd查看端口占用、相应进程、杀死进程等的命令【转】
- Android 最火的快速开发框架androidannotations配置详解
- 深入详解Struts2——使用注解配置Action
- Android AndroidStudio开发全部套件百度网盘下载
- UserScoreSignServiceImpl 代码记录
- get和load的区别
- c#习题之2
- 炫酷照片墙----------------网站也不错的样子
- 配置错误:不能在此路径中使用此配置节。如果在父级别上锁定了该节,便会出现这种情况。锁定是默认设置的
- ios如何将model转换成NSDictionary
- OC 字典属性和方法
- awk 注释
- Face-vertex meshes