From 695188fe0d38df0b8d04ada5b589e8c74a39883f Mon Sep 17 00:00:00 2001 From: "Allen.Guo" <5418150+toddlerya@users.noreply.github.com> Date: Mon, 5 Mar 2018 16:54:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BB=A3=E7=A0=81bug-->=20ex?= =?UTF-8?q?ercises/chapter=5F7/remove=5Fslice.go=20(#433)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 修复代码bug, 切片取值错误导致结果偏差,丢失最后一个元素,优化创建切片的容量,避免每次自动扩容1个大小 * 使用切片完成操作 --- eBook/exercises/chapter_7/remove_slice.go | 4 ++-- eBook/exercises/chapter_7/split_string.go | 27 +++++++++++++---------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/eBook/exercises/chapter_7/remove_slice.go b/eBook/exercises/chapter_7/remove_slice.go index 7e3724d..0749c26 100755 --- a/eBook/exercises/chapter_7/remove_slice.go +++ b/eBook/exercises/chapter_7/remove_slice.go @@ -12,8 +12,8 @@ func main() { } 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]) - copy(result[at:], slice[end:]) + copy(result[at:], slice[end+1:]) return result } diff --git a/eBook/exercises/chapter_7/split_string.go b/eBook/exercises/chapter_7/split_string.go index c4a8c04..d7d29fa 100755 --- a/eBook/exercises/chapter_7/split_string.go +++ b/eBook/exercises/chapter_7/split_string.go @@ -1,16 +1,19 @@ package main -import "fmt" +import ( + "fmt" + ) -func main() { - str := "Google" - for i := 0; i <= len(str); i++ { - a, b := Split(str, i) - fmt.Printf("The string %s split at position %d is: %s / %s\n", str, i, a, b) - } + func main() { + rawString := "Google" + index := 3 + sp1, sp2 := splitStringbyIndex(rawString, index) + fmt.Printf("The string %s split at position %d is: %s / %s\n", rawString, index, sp1, sp2) + } -} - -func Split(s string, pos int) (string, string) { - return s[0:pos], s[pos:] -} + func splitStringbyIndex(str string, i int) (sp1, sp2 string) { + rawStrSlice := []byte(str) + sp1 = string(rawStrSlice[:i]) + sp2 = string(rawStrSlice[i:]) + return + }