Files
the-way-to-go_ZH_CN/eBook/18.1.md
Haigang Zhou fa1cfcc67f 第十七十八章 (#833)
Co-authored-by: Joe Chen <jc@unknwon.io>
2022-05-19 19:57:23 +08:00

60 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 18.1 字符串
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([]rune(str))`
5如何连接字符串
(最快速)使用 `bytes.Buffer`(参考[章节 7.2](07.2.md)
或使用 `Strings.Join()`(参考[章节 4.7](04.7.md)
或使用 `+=`
```go
str1 := "Hello "
str2 := "World!"
str1 += str2 //str1 == "Hello World!"
```
6如何解析命令行参数使用 `os` 或者 `flag` 包(参考[例 12.4](examples/chapter_12/fileinput.go)
## 链接
- [目录](directory.md)
- 上一节:[出于性能考虑的实用代码片段](18.0.md)
- 下一节:[数组和切片](18.2.md)