1. 程式人生 > >C++ string 操作

C++ string 操作

C++ 字串長度:

求字串長度用.size()或者.length()
不要用sizeof()

C++刪除string最後一個字元的幾種方法:

#include<iostream>  
#include<string>  
using namespace std;  
int main()   
{  
    string str;  
    str = "123456";  
    cout << str << endl;  

    //方法一:使用substr()  
    str = str.substr(0, str.length() - 1
); cout << str << endl; //方法二:使用erase() str.erase(str.end() - 1); cout << str << endl; //方法三:使用pop_back() str.pop_back(); cout << str << endl; return 0; }

c++ 刪除字串指定位置的字元

string erase(int start, int len); //start為要刪除字元的起始位置(從0數起),len為要刪除字元的個數。

擷取子串

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

替換子串

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

查詢子串

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)