mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-19 03:50:11 +08:00
modified: 18.1.md
new file: 18.10.md new file: 18.11.md new file: 18.2.md new file: 18.3.md new file: 18.4.md modified: 18.5.md new file: 18.6.md new file: 18.7.md new file: 18.8.md new file: 18.9.md modified: directory.md
This commit is contained in:
103
eBook/18.5.md
103
eBook/18.5.md
@@ -1,67 +1,38 @@
|
||||
# 18.1 字符串
|
||||
|
||||
(1)如何修改字符串中的一个字符:
|
||||
|
||||
```go
|
||||
str:="hello"
|
||||
c:=[]byte(s)
|
||||
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)) //TBD`
|
||||
|
||||
(5)如何连接字符串:
|
||||
|
||||
最快速: `with a 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)
|
||||
- 上一章:[运算符模板和接口](17.4.md)
|
||||
- 下一节:[字符串](18.1.md)
|
||||
|
||||
## 链接
|
||||
|
||||
- [目录](directory.md)
|
||||
- 上一章:[运算符模板和接口](17.4.md)
|
||||
# 18.5 接口
|
||||
|
||||
(1)如何检测一个值v是否实现了一个接口`Stringer`:
|
||||
|
||||
```go
|
||||
if v, ok := v.(Stringer); ok {
|
||||
fmt.Printf("implements String(): %s\n", v.String())
|
||||
}
|
||||
```
|
||||
|
||||
(2)如何使用接口实现一个类型分类函数:
|
||||
|
||||
```go
|
||||
func classifier(items ...interface{}) {
|
||||
for i, x := range items {
|
||||
switch x.(type) {
|
||||
case bool:
|
||||
fmt.Printf("param #%d is a bool\n", i)
|
||||
case float64:
|
||||
fmt.Printf("param #%d is a float64\n", i)
|
||||
case int, int64:
|
||||
fmt.Printf("param #%d is an int\n", i)
|
||||
case nil:
|
||||
fmt.Printf("param #%d is nil\n", i)
|
||||
case string:
|
||||
fmt.Printf("param #%d is a string\n", i)
|
||||
default:
|
||||
fmt.Printf("param #%d’s type is unknown\n", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 链接
|
||||
|
||||
- [目录](directory.md)
|
||||
- 上一章:[运算符模板和接口](17.4.md)
|
||||
- 下一节:[字符串](18.1.md)
|
Reference in New Issue
Block a user