# String
---
## 字串為資料型態
## 以下為詳細內容
---
## 字串形式
----
1. 數字(但不能運算
2. 字元
3. 句子
---
## Length
----
### 可利用內建函式表示字串長度
```cpp=
string s="hello, world";
cout<<s.length()<<endl; // 12
cout<<s.size()<<endl; // 12
```
----
通常以length()表示字或句子的長度
size()則用於STL containers
---
## Access
----
由於字串存取方式與陣列相同
故取特定值方法一樣
----
```cpp=
string s="hello, world";
cout<<s[5]<<endl; // ,
cout<<s[8]<<endl; // o
```
----
```cpp=
string s="hello, world";
for(int i=0;i<s.length();i++){
cout<<s[i];
}
cout<<endl;
```
----
用迴圈過於麻煩,字串可直接輸出
```cpp=
string s="hello, world";
cout<<s<<endl;
```
---
## 常用函式
----
### getline
### 用於整段輸入
```cpp=
string s; // hello, world
cin>>s;
cout<<s<<endl; // hello,
getline(cin,s);
cout<<s<<endl; //hello, world
```
----
### find&substr
```cpp=
string s="hello, world";
cout<<s.find('e')<<endl; //1
cout<<s.find('l')<<endl; //2
cout<<s.find('a')<<endl; //-1
cout<<s.find("world")<<endl; //7
string str=s(0,5);
cout<<str<<endl; // hello
```
---
## 小知識補充
----
### 字串合併
### 可直接使用運算子
```cpp=
string s1="hello,";
string s2=" world";
cout<<s1+s2<<endl; //hello, world
```
----
### 比大小
```cpp=
string s1="987";
string s2="1234";
s1>s2 ? cout<<s1<<endl : cout<<s2<<endl; //987
```
Note:
兩字串各從s1[0]及s2[0]比大小
故983>1234
若需比大小要考量兩字串整數位數
----
### 關於npos
```cpp=
int i=str.find("abc");
if(i=string::npos)
...
```
此為不完全正確的程式碼
Note:
int 應改為string::size_type
由於string::size_type描述的是size
故需為無符號整數型別
而如i=-1轉為無符號整數型別與npos的值判定不一定相同
(需看實際定義
故結果有可能為false
---
## ASCII code
----
### Try it
```cpp=
#include <iostream>
using namespace std;
int main(){
cout<<'A'-0<<endl;
}
```
---
## cctype
----
主要用來判定字元
```cpp=
#include <cctype>
int main() {
isupper() // 判斷大寫
islower() // 判斷小寫
isdigit() // 判斷數字
isalpha() // 判斷字母
isspace() // 判斷空白
toupper() // 變成大寫
tolower() // 變成小寫
}
```
----
雖然cctype很方便
但盡量還是自己寫函式用ASCII轉字元
可以省很多時間
---
{"metaMigratedAt":"2023-06-15T20:24:35.848Z","metaMigratedFrom":"YAML","breaks":true,"slideOptions":"{\"theme\":\"league\",\"transition\":\"slide\"}","title":"String - 初階教學面試","description":"數字(但不能運算","contributors":"[{\"id\":\"23ee8c8c-401f-4da6-b8a2-25f638440f4f\",\"add\":2217,\"del\":399}]"}