刪除字符串中子串
string s1="asdfgh";
s1 =s1.erase(2,3);
//則s1的字符串變爲"ash"
刪除s1中從第2個字符開始的3個字符並再次賦值給s1
字符串中插入字符串
string str1="We can insert a string";
string str2="a str into ";
//在字符串指定位置前面插入指定字符串
cout <<str1.insert(14,str2)<<endl; /*A*/
//在字符串指定位置前面插入指定字符串的子串(從指定索引開始的指定個數的字符)
cout <<str1.insert(14,str2,2,9)<<endl; /*B*/
//插入指定字符串的前n個字符
cout <<str1.insert(14,"test hello",5)<<endl; /*C*/
//插入n個相同字符到字符串中
cout <<str1.insert(14,6,'*')<<endl; /*D*/
A::::將str2插入到str1下標爲14位置處
B::::將str2的下標2開始的9個字符插入到str1的下標爲14的位置處
C::::將“test hello”的前5個字符插入到str1的下標爲14的位置處
D::::將6個‘*’字符插入到str1的下標爲14的位置處
上述的操作結果如下::::
替換字符串中子串
string ori = "his name is Tom";
string fnd = "Tom";
string rep = "Jack";
ori = ori.replace(ori.find(fnd), fnd.length(), rep);
cout<<ori<<endl;
用ori對象自帶的find函數找到fnd這個子字符串,再用ori對象的自帶的replace函數來替換,結果如下::
將string字符串轉換成char *字符串
如果要將string轉換爲char*,可以使用string提供的函數c_str() ,或是函數data(),data除了返回字符串內容外,不附加結束符’\0’,而c_str()返回一個以‘\0’結尾的字符數組。
/*錯誤做法:::::*/
char *C;
string S="123456";
C = S.c_str();
/*正確做法:::::*/
char C[20];
string S="123456";
strcpy(C,S.c_str());
c_str()函數返回一個指向正規C字符串的指針,內容與本string串相同.c_str()返回的是一個臨時指針,在S對象被析構後,C會成爲一個野指針,C指向的內容也會被改變。
從文件中逐行讀取string字符串
ifstream fin("data.txt");
string s;
while(getline(fin,s))
{
cout << "Read from file: " << s << endl;
}
getline讀取文件方式: 逐行讀取, 將行讀入字符串, 行之間用回車換行區分。
我把data.txt中寫入一些字符串,如下:::
上述代碼的執行結果::::