STL容器string基礎用法小結,stl容器string小結
//方法:append(), insert(), erase(),empty(), replace(),
// find(), compare(), empty()
//算法:reverse()
#include <iostream>
#include <string>
#include <vector> //string對象作為vector元素
#include <sstream> //istringstream ostringstream
#include <algorithm> //reverse()
using namespace std;
void showS(string s){
cout<<s<<endl<<endl;
}
template <typename T>
string convertToString(T x){ //數值轉換為string對象
ostringstream o;
o<<x;
return o.str(); //Q:為什麼返回的是0.str()?
}
template <typename T>
T convertFromString(const string& s){ //string對象轉換為數值
istringstream i(s);
T x;
i>>x;
return x;
}
int main(){
string s;
s+="abc";
cout<<s<<endl<<endl; //輸出 abc
s.append("123"); //尾部追加
showS(s); //輸出 abc123
cout<<s[2]<<endl; //下標訪問
s.insert(s.begin()+1,'m'); //插入
showS(s); //輸出 ambc123
cout<<s.length()<<endl; //長度 7
s.erase(s.begin()+2,s.begin()+4);
//刪除
showS(s); //輸出 am123
s=""; //清空
cout<<s.empty()<<endl; //是否為空 1
//-----------------------------------------------
s="abc123456";
showS(s); //輸出 abc123456
s.replace(3,3,"good"); //替換
showS(s); //輸出 abcgood456
cout<<s.find("cg")<<endl //輸出 2 //尋找
<<s.find("bb")<<endl; //輸出 4294967295
cout<<s.compare("abcgo")<<endl //比較,s大,1
<<s.compare("abcgood456")<<endl //相等,0
<<s.compare("bbc")<<endl; //s小,-1
reverse(s.begin(),s.begin()+3); //使用reverse反向排序
showS(s); //輸出 cbagood123456
string birth=convertToString(1997); //數值轉換為string對象
showS(birth); //輸出1997
string dd="7.18";
double p=convertFromString<double>(dd); //string對象轉換為數值
cout<<p<<endl; //輸出7.18
//-----------------------------------------------
vector<string> v; //string對象作為vector元素
v.push_back("Benz");
v.push_back("Audi");
v.push_back("BMW");
cout<<v[0]<<' '<<v[1]<<' '<<v[2]<<endl; //輸出 Benz Audi BMW
cout<<v[0][0]<<' '<<v[1][1]<<endl; //輸出 B u
cout<<v[2].length()<<endl; //輸出 3
return 0;
}