C++中搜索、截取字符串

jopen 10年前發布 | 36K 次閱讀 C/C++開發 C/C++

    #include <iostream>

#include <string>  
using std::cout;  
using std::endl;  
using std::string;  
int main(void){  
    string str1="hi,test,hello";  
    string str2="test";  
    //搜索子串,返回子串第一個字符的索引  
    cout << str1.find(str2)<<endl;  
    //如果不存在,返回內置常量string::npos,在一些編譯器中通常為4294967295  
    cout << str1.find('k')<<endl;  
    //從指定索引開始搜索  
    cout <<str1.find('h',2)<<endl;  
    //從指定索引搜索指定字符串的前n個字符  
    cout <<str1.find("her",1,2)<<endl;  

    //在指定字符集合中搜索字符,返回其索引  
    cout <<str1.find_first_of("AaEeIiOoUu")<<endl;  
         //從指定索引處開始在指定字符集合中搜索字符  
    cout <<str1.find_first_of("AaEeIiOoUu",2)<<endl;  
         //從指定索引處開始在指定字符集合中搜索指定長度字符  
    cout <<str1.find_first_of("AaEeIiOoUu",2,2)<<endl;  

    //在指定字符集合中逆向搜索字符,返回字符最后索引,同樣也具有上面另外兩個重載方法  
    cout <<str1.find_last_of("AaEeIiOoUu")<<endl;  

    //查找字符串中第一個不在字符集合中的字符  
    cout <<str1.find_first_not_of("AaEeIiOoUu")<<endl;  
    //查找字符串中最后一個不在字符集合中的字符  
    cout <<str1.find_last_not_of("AaEeIiOoUu")<<endl;  

    //逆向搜索,也具有和find()一樣的重載方法  
    cout <<str1.rfind('l')<<endl;  

    //截取子串  
    string str3=str1.substr(3,4);  
    cout <<str3<<endl;  
    return 0;  

}  </pre><br />
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!