c++string函式總結
阿新 • • 發佈:2018-11-25
總結一些string函式:
insert():
string a="qwe";
string b="asd";
a.insert(2,b);
cout<<a;
輸出:qwasde
erase():
string a="qwe";
a.erase(0,1);//刪除第一個字元
cout<<a;
結果:we
replace():
string a="qwe";
a.replace(2,3,"dfg");//將a的第2個位置後的三個字元替換為dfg,沒有的補上
cout<<a;
輸出:qwdfg
find()和rfind();
string a="qwereet"; int b = a.find('e');//字元也可以,返回找到第一個字元的位置,若找不到,返回-1,也就是string::npos int c = a.find("re"); cout<<b<<" "<<c;
輸出:2 3
rfind():到著找
string a="qwwreet";
int b = a.rfind('e');
int c = a.rfind("re");//第一個r的位置在倒數第三個
cout<<b<<" "<<c;
輸出:5 3
find_first_of()與find_last_of():
//將字串中所有的母音字母換成* //程式碼來自C++ Reference,地址:http://www.cplusplus.com/reference/string/basic_string/find_first_of/ #include<iostream> #include<string> using namespace std; int main() { std::string str("PLease, replace the vowels in this sentence by asterisks."); std::string::size_type found = str.find_first_of("aeiou"); while (found != std::string::npos) { str[found] = '*'; found = str.find_first_of("aeiou", found + 1); } std::cout << str << '\n'; return 0; } //執行結果: //PL**s* r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks
find_last_of 倒著找
find_first_not_of()與find_last_not_of():
感覺和前面一類的相反的,類似於找了個補集。即在a中搜尋b中沒有的字元並返回位置
#include<bits/stdc++.h> using namespace std; int main(){ string str("PLease, replace the vowels in this sentence by asterisks."); int found = str.find_first_not_of("aeiou"); while (found != -1){ str[found] = '*'; found = str.find_first_not_of("aeiou", found + 1); } cout << str; return 0; } 輸出:**ea*e***e**a*e***e**o*e***i****i***e**e**e****a**e*i****
string轉int:
#include<bits/stdc++.h>
using namespace std;
int main(){
string a="123";
int c = atoi(a.c_str());//atoi傳入的引數必須是char*,所以c_str返回一個char * char型別的指標
cout<<c;
return 0;
}
輸出:123