# 字串

不管在什麼程式裡，文字的處理都是很重要的一部分，在這裡我們會認識一些跟字串打交道的方法

## substring

substring可以讓我們擷取自串裡面的一小段文字，把這一小段文字變成新的字串丟出來給我們：

```kotlin
fun main() {
    val className = "Kuro's class"
    val indexOfApostrophe = className.indexOf('\'')
    val teacherName = className.substring(0 until indexOfApostrophe)
    println(teacherName)
}
```

在indexOf裡面我們看到我們尋找的字元是 '\\'' ，這是因為我們要尋找的單引號是一個有特殊意義的字元，所以我們不能直接使用 ''' ，這樣編譯器沒辦法知道我們是想用字元符號還是文字的單引號。所以我們需要在前面加上一個跳脫字元(\\)來跟編譯器說後面這一個字是一個文字，而不是一個有特殊意義的符號。接下來我們來認識一些常用的跳脫字元組成的特殊文字：

| 特殊意義文字 | 描述        |
| ------ | --------- |
| \t     | Tab鍵      |
| \b     | 退回鍵       |
| \n     | 換行        |
| \\"    | 雙引號       |
| \\'    | 單引號       |
| \\\\   | 反斜線       |
| \\$    | 錢字號       |
| \u     | Unicode字元 |

## equals(==)

equals(==)可以比對兩個字串是不是“完全相等”：

```kotlin
fun main() {
    val name = "Kuro"
    println("Hello, $name!" == "Hello, Kuro!")
    println("Hello, $name!" == "Hi, Kuro!")
}
```

## matches

matches可以比對字串是不是符合“特定格式”：

```kotlin
fun main() {
    val phoneNumber = "0933225511"
    println(phoneNumber.matches(Regex("^(0|[+]886)9\\d{8}$")))
    // 檢測是不是符合台灣手機格式
}
```

這邊我們看到了一串看起來很複雜的文字("^(0|\[+]886)9\\\d{8}$")這個我們稱呼他為“正規表示式”，這邊我們使用下面的工具網站來介紹什麼事正規表示式

[正規表示式](https://regexr.com/)

## replace

replace有四種模式，接下來的範例可以來比較四種模式的差別：

```kotlin
fun main() {
    val text = "abcdefghi"
    println(text.replace('a', 'e'))
    println(text.replace("ab", "de"))
    println(text.replace(Regex("[aeiou]"), "ww"))
    println(text.replace(Regex("[aeiou]")){ it.value.uppercase() })
}
```

## split

split可以讓我們用某幾個字元把整個字串切開來變成一個字串列表：

```kotlin
fun main() {
    val numberText = "1/3/5/7/9/10"
    val numbers = numberText.split('/')
    for (number in numbers) {
        println(number)
    }
}
```

另外split也支援字串跟正規表示式的切割，使用方法是一樣的，我們可以自行試試看比較差異

## Unicode

Unicode中文叫做萬國碼，是一個由非營利機構Unicode聯盟維護的字元編碼。創立這個字元編碼的宗旨就是“讓Unicode編碼取代現有的其他字元編碼”，因為現有的其他編碼沒辦法擴充空間有限，而且沒辦法支援多種語言。目前最新的版本為2023年9月12日發布的15.1.0版本，總共收錄了149,813個字元。下面我們來介紹要怎麼使用Unicode字元：

[Unicode字元表](https://symbl.cc/en/unicode-table)

```kotlin
fun main() {
    val text = "\u2235"
    println(text)
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kuroclass.gitbook.io/kotlin/ch9/zi-chuan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
