23、【C++基礎】compare函數的使用


compare函數用來進行字符串以及其子串的比較,示例如下:

#include <iostream>  
#include <string>  
#include <cctype>  
using std::cout;  
using std::endl;  
using std::cin;  
using std::string;  
int main(void){  
    string str1="hi,test,hello";  
    string str2="hi,test";  
    //字符串比較  
    if(str1.compare(str2)>0)  
        printf("str1>str2\n");  
    else if(str1.compare(str2)<0)  
        printf("str1<str2\n");  
    else  
        printf("str1==str2\n");  
      
    //str1的子串(從索引3開始,包含4個字符)與str2進行比較  
    if(str1.compare(3,4,str2)==0)  
        printf("str1的指定子串等於str2\n");  
    else  
        printf("str1的指定子串不等於str2\n");  
      
    //str1指定子串與str2的指定子串進行比較  
    if(str1.compare(3,4,str2,3,4)==0)  
        printf("str1的指定子串等於str2的指定子串\n");  
    else  
        printf("str1的指定子串不等於str2的指定子串\n");  
      
    //str1指定子串與字符串的前n個字符進行比較  
    if(str1.compare(0,2,"hi,hello",2)==0)  
        printf("str1的指定子串等於指定字符串的前2個字符組成的子串\n");  
    else  
        printf("str1的指定子串不等於指定字符串的前2個字符組成的子串\n");  
    return 0;  
      
}  

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM