<分区>
我有一段字符串,我想删除一个特定的字符串。
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 中的任何元素一样删除它。
找到它是一个线性搜索。删除是以下之一 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]
关于string - 从 Go 中的 slice 中删除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896190/