1. 程式人生 > 其它 >c++ STL string函式小整理

c++ STL string函式小整理

1.長度:s.length(),s.size();

2.比較:直接用四則運算子即可

3.複製,連線:=,+;

4.是否空:s.empty();

5.求子串:s.substr(pos=0,pos!=0.size(int pos=0,int n=npos)返回pos開始的n個字元組成的字串

1 int main (){
2     string s = "hello, world!";
3     string ss1 = s.substr(2);        //llo, world!
4     string ss2 = s.substr(2,3);        //llo
5     cout << ss1 << endl << ss2 << endl;
6 }

6.刪除字元:s.erase(int pos=0,int n=npos)刪除pos開始的n個字元,返回修改後的字串,同時源字串也被修改

1 int main (){
2     string s = "hello,world!";
3     string ss1 = s.erase(6);    //刪除下標為6的字元開始的所有字元,hello,
4     string ss2 = s.erase(1,2);    //刪除下標為2的字元開始的2個字元,刪除el 
5     cout << s << endl << ss1 << endl << ss2 << endl;
6 }

7.s.insert()插入字串

1     string s=",";
2     s.insert(0,"heo"); cout<<s<<endl;//整個字串
3     s.insert(4,"world",2); cout<<s<<endl;//world的前2個字元
4     s.insert(2,2,'l');cout<<s<<endl;//插入單個字元2次 
5     s.insert(s.end(),'r');cout<<s<<endl;//使用迭代器
6     s += "ld!
";cout<<s<<endl;//在開頭或者末尾插入最好還是運算子 7

8.s.replace()字串替代

用str替代指定字串從起始位置pos開始長度為len的字元

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = "abcdefghigk";
    str=str.replace(str.find("c"),2,"#");  //從第一個a位置開始的兩個字元替換成#
    cout<<str<<endl; 
    return 0;
}

 

9.s.substr()字串替代

用substr的指定字串(給定起始位置和長度)替換從指定位置上的字串

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = "he is@ a@ good boy";
    string substr = "12345";
    str=str.replace(0,5,substr,substr.find("1"),4); //用substr的指定字串替換str指定字串
    cout << str << endl;
    return 0; 
}

10.s.find()字串查詢

s.find()用來找出字元在字串中的位置

s.find(str,position)

str表示要查詢的元素

position表示字串的某個位置,表示從這個位置開始的字串中找指定元素

這個可以不填,那就預設從字串的開始進行查找了

返回值是目標字元的位置,沒有找到目標元素就返回string::npos。(或-1)

 1 #include<iostream>
 2 #include<bits/stdc++.h>
 3 using namespace std;
 4 typedef  long long ll;
 5 int main(){
 6     int a[10]={1,2,3,4,5,6};
 7     string s="abcdefg";
 8     cout << find(a,a+10,3)-a << endl;
 9     cout << s.find('e') << endl;
10     cout << s.find("bcd") << endl;
11     cout << s.find('e',4) << endl;//從下標為4開始搜尋,輸出-1;
12     return 0;
13 } 

11.字串的反轉函式s.reverse()

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef  long long ll;
int main(){
    char a[8]={"abcdefg"};
    string s="abcdefg";
    cout << "string reverse用法:reverse(s.begin(),s.end());" << endl;
    reverse(s.begin(),s.end());
    cout << s << endl; 
    cout << "字串陣列 reverse用法:reverse(a,a+10);" << endl;
    reverse(a,a+7);    
    for(int i=0;i<7;i++){
        cout << a[i];
    }
    return 0;
} 

----------------------------------先更到這,回宿舍在更