stirng型別
簡介:
C++標準庫提供的型別:string
長度可變的字串
操作簡單
?僅為包含個人常用函式
頭檔案
string 型別與其它的標準庫型別相同,都需要包含對應的頭檔案
#include<string>
using namespace std;
string 型別的定義和初始化
| 定義及初始化 | 解釋 |
|---|---|
| string s1 = "C++"; | 創建字串s1, 如果省略 = "C++" 則為空串 |
| stirng s2(s1); | 創建字串s2并初始化值為s1的值(C++) |
| string s3("Love") | 創建字串s3并初始化為 Love |
| string s4(6,'I') | 創建字串s4并初始化為連續6個字符為'I',組成的字串 |
string 型別的函式
-
字串的賦值
string s1 = "I LOVE C++"; string s2; s2 = s1; cout<<s2;輸入及輸出:
I LOVE C++
-
字串的 +,+= 運算子
string s1 = "I "; string s2 = "LOVE "; string s3 = "C++"; s1 = s1 + s2; cout<<s1<<endl; s1 += s3; cout<<s1<<endl;輸入及輸出:
I LOVE
I LOVE C++ -
字串的關系運算子
string 型別可以直接使用==,!=,>,<,>=,<=等關系運算子來進行字串的比較,并回傳布爾型別
//EG: string s1 = "123"; string s2 = "123"; cout<<(s1 == s2 ? "s1 = s2" : "s1 != s2");輸入及輸出:
s1 = s2
-
字串的讀取
-
cin方式
讀取時自動忽略開頭的空白字符
當讀取到字符后一旦遇到空白字符,結束讀取string s1; cin>>s1; cout<<s1;輸入及輸出:
Hello World
Hello -
getline方式
包含在 string 庫內
-
istream& getline (istream& is, string& str);string str; getline(cin,str); cout<<str;輸入及輸出:
Hello World
abc
Hello World每次輸入為一行, 遇到'\n'結束輸入
-
istream& getline (istream& is, string& str, char delim);string str; getline(cin,str,'#'); cout<<str;輸入及輸出:
abc def#abc
abc def當以'#'為結尾術符,'#'及'#'以后的字符就不再讀取
-
-
-
字串長度
size()/lenth()均可, 回傳該字串的長度(位元組長度)
string s1; cout<<s1.size()<<endl; cout<<s1.lenth()<<endl; s1 = "Hello World"; cout<<s1.size()<<endl; cout<<s1.lenth()<<endl; s1 = "你好"; cout<<s1.size()<<endl; cout<<s1.lenth()<<endl;輸入及輸出:
0
0
11
11
4
4 -
字串獲取字符
str[n]:回傳str中的第n個字符,從0到size()-1
string str = "I Love C++" cout<<str[0]<<endl; a[7] = 'A'; cout<<str;輸入及輸出:
I
I Love A++ -
字串判空
empty() 回傳布爾型別
string s1; if(s1.empty()) cout<<"s1字串為空";輸入及輸出:
s1字串為空
-
字串查找
string中的find()回傳值是第一次字符或字串出現的下標,如果沒找到,那么會回傳npos,
string s1 = "C++"; string s2 = "I LOVE C++"; cout<<s1.find(s2)<<endl; cout<<s1.find("Hello")<<endl;輸入及輸出:
7
4294967295 (極大的值或極小的值) -
字串內的排序
string str = "cba"; sort(str.begin(), str.end()); cout<<str;輸入及輸出:
abc
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/82048.html
標籤:C++
上一篇:如何申請騰訊地圖用戶Key
