> For the complete documentation index, see [llms.txt](https://ryanyang.gitbook.io/the-way-to-go-zh-cn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ryanyang.gitbook.io/the-way-to-go-zh-cn/di-si-bu-fen-shi-ji-ying-yong/18.0/18.1.md).

# 字符串

（1）如何修改字符串中的一个字符：

```go
str:="hello"
c:=[]byte(str)
c[0]='c'
s2:= string(c) // s2 == "cello"
```

（2）如何获取字符串的子串：

```go
substr := str[n:m]
```

（3）如何使用`for`或者`for-range`遍历一个字符串：

```go
// gives only the bytes:
for i:=0; i < len(str); i++ {
… = str[i]
}
// gives the Unicode characters:
for ix, ch := range str {
…
}
```

（4）如何获取一个字符串的字节数：`len(str)`

如何获取一个字符串的字符数：

最快速：`utf8.RuneCountInString(str)`

`len([]int(str))`

（5）如何连接字符串：

最快速： `with a bytes.Buffer`（参考[章节7.2](/the-way-to-go-zh-cn/di-er-bu-fen-yu-yan-de-he-xin-jie-gou-yu-ji-shu/07.0/07.2.md)）

`Strings.Join()`（参考[章节4.7](/the-way-to-go-zh-cn/di-er-bu-fen-yu-yan-de-he-xin-jie-gou-yu-ji-shu/di-4-zhang-ji-ben-jie-gou-he-ji-ben-shu-ju-lei-xing/04.7.md)）

使用`+=`：

```go
 str1 := "Hello " 
 str2 := "World!"
 str1 += str2 //str1 == "Hello World!"
```

（6）如何解析命令行参数：使用`os`或者`flag`包

（参考[例12.4](https://github.com/yangchuansheng/the-way-to-go_ZH_CN/tree/f30ab7d8c58f85840a0afb548024b93642b518d5/eBook/examples/chapter_12/fileinput.go)）

## 链接

* [目录](https://github.com/yangchuansheng/the-way-to-go_ZH_CN/tree/f30ab7d8c58f85840a0afb548024b93642b518d5/eBook/directory.md)
* 上一节：[出于性能考虑的实用代码片段](/the-way-to-go-zh-cn/di-si-bu-fen-shi-ji-ying-yong/18.0.md)
* 下一节：[数组和切片](/the-way-to-go-zh-cn/di-si-bu-fen-shi-ji-ying-yong/18.0/18.2.md)
