ch3: fix code path

This commit is contained in:
chai2010
2016-01-20 23:25:13 +08:00
parent 7fe7a309be
commit ca0f87fad9
5 changed files with 9 additions and 31 deletions

View File

@@ -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** 編寫一個函數,判斷兩個字符串是否是是相互打亂的,也就是説它們有着相同的字符,但是對應不同的順序。