C++ 中字符串查找、字符串截取、字符串替換


參照:C++基礎-string截取、替換、查找子串函數

1、字符串查找

 s.find(s1)         //查找s中第一次出現s1的位置,並返回(包括0)

 s.rfind(s1)        //查找s中最后次出現s1的位置,並返回(包括0)

 s.find_first_of(s1)       //查找在s1中任意一個字符在s中第一次出現的位置,並返回(包括0)

s.find_last_of(s1)       //查找在s1中任意一個字符在s中最后一次出現的位置,並返回(包括0)

s.fin_first_not_of(s1)         //查找s中第一個不屬於s1中的字符的位置,並返回(包括0)

s.fin_last_not_of(s1)         //查找s中最后一個不屬於s1中的字符的位置,並返回(包括0)

2、字符串截取

s.substr(pos, n)    //截取s中從pos開始(包括0)的n個字符的子串,並返回

s.substr(pos)        //截取s中從從pos開始(包括0)到末尾的所有字符的子串,並返回

3、字符串替換

 s.replace(pos, n, s1)     //用s1替換s中從pos開始(包括0)的n個字符的子串

4、代碼測試(字符串操作.cpp)

#include <iostream>
using namespace std;

/* 字符串查找 */ 
void findSubString(string str){
    // find()函數的使用,返回查找對象第一次出現的位置.  
    cout << str.find("fs") << endl;
    // rfind()函數的使用,返回查找對象最后出現的位置
    cout << str.rfind("s") << endl;
}

/* 字符串截取 */ 
void getSubString(string str){
    // substr(pos)函數的使用,返回從pos開始(包含pos位置的字符)所有的字符
    cout << str.substr(2) << endl;
    // substr(pos,n),返回從pos開始(包含pos位置的字符)n個字符
    cout << str.substr(2, 2) << endl;
}

/* 字符串替換 */ 
void replaceString(string str){
    // replace(pos,n,s1),用s1替換從pos開始的n個字符
    cout << str.replace(0,2,"xiaoming") << endl;
}

int main()
{
    string str = string("sdfsf");
    // findSubString(str);
    // getSubString(str);
    replaceString(str);
    return 0;
}

5、字符替換(用x替換字符串中所有的a.cpp)

#include <iostream>
using namespace std;

/* 用x替換a */
void replaceAWithX(string str){
    int pos;
    pos = str.find("a");
    while(pos != -1){
        // str.length()求字符的長度,注意str必須是string類型
        str.replace(pos,string("a").length(),"x");
        pos = str.find("a");
    }

    cout << str << endl;
}

int main()
{
    string str = string("fsafsdf");
    replaceAWithX(str);
    return 0;
}


免責聲明!

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



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