第一週string學習總結
阿新 • • 發佈:2021-01-19
技術標籤:c++
C++ String類
關於string
一·定義字串變數
和其他型別變數一樣,字串變數必須先定義後使用,定義字串變數要用類名string。要使用string類的功能時,必須在本檔案的開頭將C++標準庫中的string標頭檔案包含進來,即應加上
#include< string >…注意標頭檔案名不是string.h
二·字串變數的輸入輸出
可以在輸入輸出語句中用字串變數名,輸入輸出字串,如
cin>> string1; //從鍵盤輸入一個字串給字串變數string1
三·字串變數的運算
(1)string賦值
- 用等號賦值
string1=string2;
其作用與“strcpy(string1,string2);”相同。
string s1("angle");
string s2;
s2=s1;
cout<<s2;//輸出angle
- 用assign()複製
string s1("angle"); string s2; s2.assign(s1); cout<<s2;//輸出angle //從s1中下標為0的字元開始複製3個字元 s2.assign(s1,0,3); cout<<s2;//輸出ang return 0;
(2)比較string大小
- compare函式可以用來比較string的大小
string string1="angle";
string string2="awful";
cout<<string1.compare(string2)<<endl;
- 直接使用關係運算符
如 ==(等於)、>(大於)、<(小於)、!=(不等於)、>=(大於或等於)、<=(小於或等於)等關係運算符來進行字串的比較。
(3)刪除string中的字元
- 使用erase()函式
(4)替換string的字元
- 使用replace()函式
(5)在string中插入字元
-
使用insert
-
insert函式多種形式
string &insert(int p0, const char *s);
//在p0處插入字串sstring &insert(int p0, const char *s, int n);
//在p0處插入字串s的前n個字元string &insert(int p0,const string &s);
//在p0處插入字串sstring &insert(int p0,const string &s, int pos, int n);
//在p0處插入字串s從pos開始的連續n個字元string &insert(int p0, int n, char c);
//在p0處插入n個字元cvoid insert(iterator it, int n, char c);
//在it處插入n個字元c
(6)取字串的字串及交換兩個字串位置
- 用substr函式和swap函式