mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 03:55:28 +08:00
修复代码bug--> exercises/chapter_7/remove_slice.go (#433)
* 修复代码bug, 切片取值错误导致结果偏差,丢失最后一个元素,优化创建切片的容量,避免每次自动扩容1个大小 * 使用切片完成操作
This commit is contained in:
@@ -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
|
||||||
}
|
}
|
||||||
|
@@ -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
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user