# 字串處理
<span>''表示字元<!-- .element: class="fragment" data-fragment-index="1" --></span>
<span>""表示字串<!-- .element: class="fragment" data-fragment-index="2" --></span>
---
## Char陣列
宣告:
```cpp
char s[n];
```
可以儲存<span style="color:red">n-1</span>個字元
----
### 使用方法:輸入
```cpp
cin >> s;
```
此方法可以接收一個字串,系統會利用換行、空格來判斷字串長度
----
### 使用方法:輸出
```cpp
cout << s;
```
----
### '\0'
<span>儲存方法:陣列<!-- .element: class="fragment" data-fragment-index="1" --></span>
<span>系統不知道字串結尾在哪<!-- .element: class="fragment" data-fragment-index="2" --></span>
<span>字串結尾會有一個'\0'符號以表示字串尾端在哪<!-- .element: class="fragment" data-fragment-index="3" --></span>
----
#### 舉例
有一字串:"`abcd`"
char陣列儲存格式為:
| Index | 0 | 1 | 2 | 3 | 4 |
| :-----: | :-----: | :-----: | :-----: | :-----:| :-----:|
| Value |'a'|'b'|'c'|'d'|<span style="color:red">'\0'</span>|
----
### 讀寫
與之前介紹陣列做法相同
`s[i]`可以讀取第$i$個元素
也可以直接對元素做個別修改
Ex. `s[i]='1';`
----
### Char陣列缺點
1. <span>字串最大長度在陣列宣告時就決定<!-- .element: class="fragment" data-fragment-index="1" --></span>
2. <span>字串相加時實作複雜 ("abc" + "def" = "abcdef")<!-- .element: class="fragment" data-fragment-index="2" --></span>
---
## String型態
宣告:
```cpp
string s;
```
* 儲存字串長度理論上<span style="color:red">無限制</span>
* 需要`#include <string>`
----
### 使用方法:輸入輸出
```cpp
cin >> s;
cout << s;
```
與char陣列一致,皆為輸出或輸入單一字串
----
### 讀寫
使用方法與Char陣列相同,支援陣列方式讀寫
Ex:
```cpp
cout << s[0];
s[0] = 'a';
```
須注意`[]`裡面數字要在<span style="color:red">0~字串長度-1</span>之間
----
### 常用寫法
```cpp=
int len = s.length(); // 回傳s長度
string s2 = s; // 令s2 = s
string s3 = s + s; // 字串相加
s == "Hello" // 判斷s是否為"Hello"
```
----
### getline()
接收整行輸入
```cpp=
string s;
getline(cin, s);
```
Ex: 輸入為`"abc def"`
| 輸入方式 | `cin >> s` | `getline(cin, s)` |
| :-----: | :-----: | :-----:|
| 值 | `"abc"` | `"abc def"` |
---
## Zerojudge a001
> 請寫一個程式,可以讀入指定的字串,並且輸出指定的字串。
| 範例輸入 | 範例輸出 |
| :-----: | :-----: |
|world|hello, world|
|C++|hello, C++|
|mary|hello, mary|
----
### 題解
每一次輸入為字串 => 使用string字串型態
```cpp=
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
while (cin >> s) {
cout << "Hello, " + s << endl;
}
return 0;
}
```
<span>這裡使用string的「相加」功能<!-- .element: class="fragment" data-fragment-index="1" --></span>
---
# 問卷
* goo.gl/V2748f
* goo.gl/HNLqVZ
{"metaMigratedAt":"2023-06-14T18:41:47.532Z","metaMigratedFrom":"YAML","title":"字串處理","breaks":true,"slideOptions":"{\"transition\":\"zoom\"}","contributors":"[{\"id\":\"2308ee1b-d046-4851-80ab-090ecbeaf503\",\"add\":2801,\"del\":393},{\"id\":\"bc51f020-0878-4119-b518-bf79c1bae9e8\",\"add\":1,\"del\":42}]"}