mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2026-01-17 04:37:14 +08:00
ch3: fix code path
This commit is contained in:
@@ -18,8 +18,8 @@ fmt.Println(basename("abc")) // "abc"
|
||||
|
||||
第一個版本併沒有使用任何庫,全部手工硬編碼實現:
|
||||
|
||||
<u><i>gopl.io/ch3/basename1</i></u>
|
||||
```Go
|
||||
gopl.io/ch3/basename1
|
||||
// basename removes directory components and a .suffix.
|
||||
// e.g., a => a, a.go => a, a/b/c.go => c, a/b.c.go => b.c
|
||||
func basename(s string) string {
|
||||
@@ -43,9 +43,8 @@ func basename(s string) string {
|
||||
|
||||
簡化個版本使用了strings.LastIndex庫函數:
|
||||
|
||||
<u><i>gopl.io/ch3/basename2</i></u>
|
||||
```Go
|
||||
gopl.io/ch3/basename2
|
||||
|
||||
func basename(s string) string {
|
||||
slash := strings.LastIndex(s, "/") // -1 if "/" not found
|
||||
s = s[slash+1:]
|
||||
@@ -60,9 +59,8 @@ path和path/filepath包提供了關於文件路徑名更一般的函數操作。
|
||||
|
||||
讓我們繼續另一個字符串的例子。函數的功能是將一個表示整值的字符串,每隔三個字符插入一個逗號分隔符,例如“12345”處理後成爲“12,345”。這個版本隻適用於整數類型;支持浮點數類型的支持留作練習。
|
||||
|
||||
<u><i>gopl.io/ch3/comma</i></u>
|
||||
```Go
|
||||
gopl.io/ch3/comma
|
||||
|
||||
// comma inserts commas in a non-negative decimal integer string.
|
||||
func comma(s string) string {
|
||||
n := len(s)
|
||||
@@ -113,9 +111,8 @@ func Join(s [][]byte, sep []byte) []byte
|
||||
|
||||
bytes包還提供了Buffer類型用於字節slice的緩存。一個Buffer開始是空的,但是隨着string、byte或[]byte等類型數據的寫入可以動態增長,一個bytes.Buffer變量併不需要處理化,因爲零值也是有效的:
|
||||
|
||||
<u><i>gopl.io/ch3/printints</i></u>
|
||||
```Go
|
||||
gopl.io/ch3/printints
|
||||
|
||||
// intsToString is like fmt.Sprint(values) but adds commas.
|
||||
func intsToString(values []int) string {
|
||||
var buf bytes.Buffer
|
||||
@@ -144,7 +141,3 @@ bytes.Buffer類型有着很多實用的功能,我們在第七章討論接口
|
||||
**練習 3.11:** 完善comma函數,以支持浮點數處理和一個可選的正負號的處理。
|
||||
|
||||
**練習 3.12:** 編寫一個函數,判斷兩個字符串是否是是相互打亂的,也就是説它們有着相同的字符,但是對應不同的順序。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user