【发布时间】:2016-03-08 07:48:10
【问题描述】:
我有一段字符串,我想删除一个特定的。
strings := []string
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")
现在如何从strings 中删除字符串"two"?
【问题讨论】:
我有一段字符串,我想删除一个特定的。
strings := []string
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")
现在如何从strings 中删除字符串"two"?
【问题讨论】:
找到要删除的元素,然后像从任何其他切片中删除任何元素一样删除它。
找到它是一个线性搜索。删除是以下slice tricks之一:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
这是完整的解决方案(在Go Playground 上试用):
s := []string{"one", "two", "three"}
// Find and remove "two"
for i, v := range s {
if v == "two" {
s = append(s[:i], s[i+1:]...)
break
}
}
fmt.Println(s) // Prints [one three]
如果你想把它包装成一个函数:
func remove(s []string, r string) []string {
for i, v := range s {
if v == r {
return append(s[:i], s[i+1:]...)
}
}
return s
}
使用它:
s := []string{"one", "two", "three"}
s = remove(s, "two")
fmt.Println(s) // Prints [one three]
【讨论】:
s := []string{"one", "two", "two", "three"}等多次出现的情况下失败
append 是内置的,而remove 不是。特别是在处理字符串切片时,这些是标准函数,除了 C 之外,几乎所有广泛使用的语言都自带开箱即用。这种功能本来可以包含在标准库中,但必须实现多少次?我们有一个strings 库,用于将字符串类型作为符文切片进行操作。这是仅在结构上实现接口定义的问题的一部分......
[602139dfb72f0dec8cf66da6 602139dfb72f0dec8cf66da7],删除后我得到 [ 602139dfb72f0dec8cf66da6]。你可以看到我得到了一个空间。我需要修剪这个吗?以及如何?
这是一个删除特定索引处元素的函数:
package main
import "fmt"
import "errors"
func main() {
strings := []string{}
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")
strings, err := remove(strings, 1)
if err != nil {
fmt.Println("Something went wrong : ", err)
} else {
fmt.Println(strings)
}
}
func remove(s []string, index int) ([]string, error) {
if index >= len(s) {
return nil, errors.New("Out of Range Error")
}
return append(s[:index], s[index+1:]...), nil
}
【讨论】: