tags: FoShiShi

字串

What

字串就是一串的字元
可以想成是 存字元的陣列
但跟字元陣列有一些不一樣的地方
例:動態的長度、子功能眾多

When

當要存一個字串
例:句子、名字


How

陣列的語法大致相同
只是有更多的功能可以去使用

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

字串的 引入值從0開始

宣告

string 字串名稱;

其中字串長度可以不用先定義(可以動態調整)

引用字串中字元

字串名稱[位置];

其中要引用的位置(pos)必須在符合0 <= pos < 陣列長度

陣列不能夠直接輸入/輸出
字串可以直接輸入/輸出
也就是

string str; cin >> str;

是合法的


各種字串操作

字串可以直接輸入/輸出
還有一堆函式可以用
甚至可以直接用加法來加字串

輸入/輸出

上面有講可以直接輸入/輸出

string str; cin >> str; cout << str << endl;

各種函式

字串跟字元陣列的不同之一
字串有一堆子功能可以去用
(以下之字串名稱皆為str)

str.length() or str.size():回傳字串長度
str.empty():回傳字串是否為空(字串長度是否為0)
str.clear():把str設為空(清空str)
str.push_back(chr) (chr是字元型態):把chr字元str尾端加入

字串加法

string str = "aaa", str2 = "bbb"; string str3 = str + str2; cout << str3 << endl; // aaabbb string str4 = str2 + 'c'; cout << str4 << endl; // bbbc

字串可以在後面加上字串
也可以在後面加上字元

實際應用

題目1

輸入一字串str
再輸入兩數a, b(a <= a <= b < str.length())
請輸出str的第a項到第b

solution

用迴圈去依次輸出str[a] ~ str[b]

#include<iostream> using namespace std; int main() { string str; int a, b; cin >> a >. b; for(LL i = a; i <= b; i ++ ) { cout << str[i]; } cout << endl; }

題目2

輸入兩字串str, str2
請輸出str長度,str2長度
str3str後面加上str2並輸出str3
再在此字串後面加上'a'並輸出之

solution

就各種操作

#include<iostream> using namespace std; int main() { string str, str2; cin >> str >> str2; cout << str.length() << endl; cout << str2.length() << endl; string str3 = str + str2; cout << str3 << endl; str3 += 'a'; cout << str3 << endl; }