从Go中的切片中删除字符串

Pat*_*eck 2 string go slice

我有一些字符串,我想删除一个特定的字符串.

strings := []string
strings = append(strings, "one")
strings = append(strings, "two")
strings = append(strings, "three")
Run Code Online (Sandbox Code Playgroud)

现在,我怎么去除串"two"strings

icz*_*cza 9

找到要删除的元素并将其删除,就像从任何其他切片中的任何元素一样.

找到它是线性搜索.删除是以下切片技巧之一:

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)

  • 为了捍卫@Stanislav,我知道他来自哪里。我不知道为什么“append”是内置的,而“remove”不是。特别是,在处理字符串切片时,这些是标准函数,几乎除 C 之外广泛使用的每种语言都带有开箱即用的函数。当这种函数本来可以包含在标准库中时,需要实现多少次?我们有一个“strings”库,用于将字符串类型作为符文片段进行操作。这是接口定义仅在结构上实现的问题的一部分...... (2认同)