簡介
String 是 STL 內含的一個容器,專門用來放字符,有許多方便的字串操作。可以想像成它是一個強化版的 Vector,其實他們的構造也非常像,核心都是使用動態陣列存放資料。它除了擁有和 Vector 相似的特性外,還加載了許多 Operator。因為之前介紹過 Vector 了,所以本篇會著重在介紹其他的功能,Vector 能使用的函式 String 大部分都能使用,想了解的可以參考本篇文章:C++ Vector 介紹。
使用方式
include
使用前需要先 #include <string>
變數宣告
成員函式
str1 = str2
:將 str2 的內容放進 str1。
str1 += str2
:將 str2 接在 str1 後。
str1 == str2
:若 str1 的內容和 str2 相等則回傳 True
,反之則回傳 False
。
str1.find(str2)
:在 str1 內尋找 str2 並回傳第一個字符位置的值。
str1.find_first_of(str2)
:在 str1 內從頭尋找 str2 內的字符並回傳第一個字符位置的值。
str1.find_last_of(str2)
:在 str1 內從尾尋找 str2 內的字符並回傳第一個字符位置的值。
str1.find_first_not_of(str2)
:在 str1 內從頭尋找不在 str2 內的字符並回傳第一個字符位置的值。
str1.find_last_not_of(str2)
:在 str1 內從尾尋找不在 str2 內的字符並回傳第一個字符位置的值。
Iterator
begin()
:回傳一個指向 String 內第一個元素位置的 Iterator。
end()
:回傳一個指向 String 內最後一個元素後面位置的 Iterator。( 注意不是最後一個元素 )
rbegin()
:回傳一個指向 String 內最後一個元素位置的反向 Iterator。
rend()
:回傳一個指向 String 內第一個元素位置的反向 Iterator。
簡單實作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <iostream> #include <string>
using namespace std;
void print(string& str1, string& str2) { cout << "str1: " << str1 << endl; cout << "str2: " << str2 << endl << endl; }
void equal(string& str1, string& str2) { cout << "str1 == str2: "; if (str1 == str2) cout << "True" << endl << endl; else cout << "False" << endl << endl; }
int main() { string str1, str2;
str1 = "string 1"; str2 = "string 2"; print(str1, str2);
str1 += str2; print(str1, str2);
cout << "在 str1 內尋找 str2: " << str1.find(str2) << endl << endl;
equal(str1, str2); str1 = str2; equal(str1, str2);
str1 = "strings"; cout << "str1: " << str1 << endl << endl;
cout << "在 str1 內從頭尋找字符為 s 的位置: " << str1.find_first_of("s") << endl; cout << "在 str1 內從尾尋找字符為 s 的位置: " << str1.find_last_of("s") << endl << endl; cout << "在 str1 內從頭尋找字符不為 s 的位置: " << str1.find_first_not_of("s") << endl; cout << "在 str1 內從尾尋找字符不為 s 的位置: " << str1.find_last_not_of("s") << endl << endl; }
|
參考資料
string - C++ Reference
C/C++ - String 用法與心得完全攻略