string的比较查找

#include<iostream>

#include<string>

using namespace std;

int main(){

         string str1("abcde");                   //字符串初始化

         string str2("abd");

        

         cout<<(str1<str2)<<endl;                //用(str1>str2)比较字符串 (真为1假为0 )                   

         cout<<str1.compare(str2)<<endl;         //用str.compare()比较字符串 (大于为1 小于为-1 等于为0)

         cout<<str1.compare("abe")<<endl;       

         cout<<str1.compare(1,3,str2)<<endl;         //str1下标从1到3与str2的字符串作比较

         cout<<str1.compare(1,3,str2,1,2)<<endl;     //str1下标从1到2str2下标从1到3的字符串作比较

        

         char arr[5]={0};

         str1.copy(arr,1,3);                       //str.copy(arr,1起始下标,3下标个数)复制字符串

         cout<<arr<<endl;

        

         cout<<str2.find(str1,0)<<endl;            //str2.find(str1,0)在str1(下标从0)中查找str2

         cout<<str2.find('a',0)<<endl;

        

         cout<<str1.substr(1,4);                   //str1.substr(1,4)查找函数从下标为1的开始四位

         str2.swap(str1);                          //str1.swap(str2)交换字符串str1,str2

         cout<<str1<<endl;

         cout<<str2<<endl;

         cout<<(str1+str2)<<endl;                  //字符串加法

          

         system("pause");

         return 0;

}

原文地址:https://www.cnblogs.com/huoyuying/p/9672027.html