From 650e5f3d68003759393ed4034a2f75885735d568 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Thu, 9 Jul 2015 10:55:23 +0800 Subject: [PATCH] =?UTF-8?q?=E7=B2=BE=E6=A0=A1=EF=BC=9A4.6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- eBook/04.6.md | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/eBook/04.6.md b/eBook/04.6.md index 42c763a..8590a97 100644 --- a/eBook/04.6.md +++ b/eBook/04.6.md @@ -28,11 +28,11 @@ Go 支持以下 2 种形式的字面值: 一般的比较运算符(`==`、`!=`、`<`、`<=`、`>=`、`>`)通过在内存中按字节比较来实现字符串的对比。你可以通过函数 `len()` 来获取字符串所占的字节长度,例如:`len(str)`。 -字符串的内容(纯字节)可以通过标准索引法来获取,在中括号 `[]` 内写入索引,索引从 0 开始计数。 +字符串的内容(纯字节)可以通过标准索引法来获取,在中括号 `[]` 内写入索引,索引从 0 开始计数: - 字符串 str 的第 1 个字节: str[0] - 第 i 个字节: str[i] - 最后 1 个字节: str[len(str)-1] +- 字符串 str 的第 1 个字节:`str[0]` +- 第 i 个字节:`str[i]` +- 最后 1 个字节:`str[len(str)-1]` 需要注意的是,这种转换方案只对纯 ASCII 码的字符串有效。 @@ -46,16 +46,20 @@ Go 支持以下 2 种形式的字面值: 你可以通过以下方式来对代码中多行的字符串进行拼接: - str := “Beginning of the string “+ - “second part of the string” +```go +str := "Beginning of the string " + + "second part of the string" +``` 由于编译器行尾自动补全分号的缘故,加号 `+` 必须放在第一行。 拼接的简写形式 `+=` 也可以用于字符串: - s := “hel” + “lo,” - s += “world!” - fmt.Println(s) //输出 “hello, world!” +```go +s := “hel” + “lo,” +s += “world!” +fmt.Println(s) //输出 “hello, world!” +``` 在循环中使用加号 `+` 拼接字符串并不是最高效的做法,更好的办法是使用函数 `strings.Join()`(第 4.7.10 节),有没有更好地办法了?有!使用字节缓冲(`bytes.Buffer`)拼接更加给力(第 7.2.6 节)!