在Go中删除切片中的字符串 [英] Removing a string from a slice in Go
本文介绍了在Go中删除切片中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
strings:= [] string
strings = append(strings,one)
strings = append(strings,two)
strings = append(strings,three)
$ c $现在如何从中删除字符串two
字符串
?解决方案找到要移除的元素并将其从中移除任何其他切片。
发现它是一种线性搜索。删除是以下切片技巧之一:
a = append(a [:i],a [i + 1:] ...)
//或
a = a [ :i + copy(a [i:],a [i + 1:])]
是完整的解决方案(在 Go Playground 上试用):
s:= [] string {one,two,three}
// Find and如果v ==two{
s = append(s [:i],s [i + 1:]),则删除two
for v,:range s {
。 ..)
break
}
}
fmt.Println(s)//打印[one three]
如果您想将其包装到一个函数中:
func remove(s [] string,r string)[] string {
for i,v:= range s {
if v == r {
return append(s [: i],s [i + 1:] ...)
}
}
返回s
}
$ c
使用它:
s: = [] string {one,two,three}
s = remove(s,two)
fmt.Println(s)//打印[one three]
I have a slice of strings, and I want to remove a specific one.
strings := []string
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")
Now how can I remove the string "two"
from strings
?
解决方案 Find the element you want to remove and remove it like you would any element from any other slice.
Finding it is a linear search. Removing is one of the following slice tricks:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
Here is the complete solution (try it on the 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]
If you want to wrap it into a function:
func remove(s []string, r string) []string {
for i, v := range s {
if v == r {
return append(s[:i], s[i+1:]...)
}
}
return s
}
Using it:
s := []string{"one", "two", "three"}
s = remove(s, "two")
fmt.Println(s) // Prints [one three]
这篇关于在Go中删除切片中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文