如何比较字符串大小


 

本人水平有限,题解不到为处,请多多谅解

 

本蒟蒻谢谢大家观看

 

比较字符串大小

 即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止

char 类型比较

 

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main(){
 4     char str1[]="hello";
 5     char str2[]="hell";
 6     char str3[]="helloo";
 7     char str4[]="hello";
 8     cout<<strcmp(str1,str2)<<endl;//返回1  str1>str2 
 9     cout<<strcmp(str1,str3)<<endl;//返回-1 str1<str3
10     cout<<strcmp(str1,str4)<<endl;//返回0  str1==str4
11 }

 

 

 

 

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 char a[100010];
 4 char b[100010];
 5 int main()
 6 {
 7 cin>>a;
 8 cin>>b;
 9 //number1:
10 strcat(a,b);    
11 //连接字符串 a,b 并把 连接后的值 赋给a;
12 //number2:
13 cout<<strcmp(a,b)<<endl;
14 //  不开for循环的话只取首位,并且 : 若a==b则返回0,若a>b则返回1,若a<b则返回-1;
15 
16 //即:两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。
17 //number3:
18 strcpy(a,b);   
19 // 将 字符串b的值 代替  a原串中的值,使得 字符串 a==b; 
20 cout<<a<<endl; 
21 }

string 类型比较

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main(){
 4     string str1="hello";
 5     string str2="helloo";
 6     string str3="hello";
 7     string str4="hell";
 8     cout<<str1.compare(str2)<<endl;//返回-1  str1<str2
 9     cout<<str1.compare(str3)<<endl;//返回0   str1==str3
10     cout<<str1.compare(str4)<<endl;//返回1   sre1>str4
11 }

 注意:无论是int 或是 char 还是 string 

赋初值都用  "   " 双引号


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM