修复代码bug--> exercises/chapter_7/remove_slice.go (#433)

* 修复代码bug, 切片取值错误导致结果偏差,丢失最后一个元素,优化创建切片的容量,避免每次自动扩容1个大小

* 使用切片完成操作
This commit is contained in:
Allen.Guo
2018-03-05 16:54:44 +08:00
committed by jc
parent f559f17fcf
commit 695188fe0d
2 changed files with 17 additions and 14 deletions

View File

@@ -12,8 +12,8 @@ func main() {
} }
func RemoveStringSlice(slice []string, start, end int) []string { func RemoveStringSlice(slice []string, start, end int) []string {
result := make([]string, len(slice)-(end-start)) result := make([]string, len(slice)-(end-start)-1)
at := copy(result, slice[:start]) at := copy(result, slice[:start])
copy(result[at:], slice[end:]) copy(result[at:], slice[end+1:])
return result return result
} }

View File

@@ -1,16 +1,19 @@
package main package main
import "fmt" import (
"fmt"
)
func main() { func main() {
str := "Google" rawString := "Google"
for i := 0; i <= len(str); i++ { index := 3
a, b := Split(str, i) sp1, sp2 := splitStringbyIndex(rawString, index)
fmt.Printf("The string %s split at position %d is: %s / %s\n", str, i, a, b) fmt.Printf("The string %s split at position %d is: %s / %s\n", rawString, index, sp1, sp2)
} }
} func splitStringbyIndex(str string, i int) (sp1, sp2 string) {
rawStrSlice := []byte(str)
func Split(s string, pos int) (string, string) { sp1 = string(rawStrSlice[:i])
return s[0:pos], s[pos:] sp2 = string(rawStrSlice[i:])
} return
}