我有一些字符串,我想删除一个特定的字符串.
strings := []string
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")
Run Code Online (Sandbox Code Playgroud)
现在,我怎么去除串"two"的strings?
找到要删除的元素并将其删除,就像从任何其他切片中的任何元素一样.
找到它是线性搜索.删除是以下切片技巧之一:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
Run Code Online (Sandbox Code Playgroud)
这是完整的解决方案(在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]
Run Code Online (Sandbox Code Playgroud)
如果要将其包装到函数中:
func remove(s []string, r string) []string {
for i, v := range s {
if v == r {
return append(s[:i], s[i+1:]...)
}
}
return s
}
Run Code Online (Sandbox Code Playgroud)
使用它:
s := []string{"one", "two", "three"}
s = remove(s, "two")
fmt.Println(s) // Prints [one three]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11667 次 |
| 最近记录: |