string - 从 Go 中的 slice 中删除字符串

标签 string go slice

<分区>

我有一段字符串,我想删除一个特定的字符串。

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/34070369/

相关文章:

javascript - 如何将所有函数参数视为字符串?

python - 通过单个索引切片多行

regex - 在参数 bash 中查找并替换字符串

c - 如何在缓冲区中设置最后一个0?

python - 如何在 Python 中将一串位转换为十六进制字符串?

go - 交叉编译共享库

go - sqlx structscan 连接查询

go - 我可以在共享结构中允许任意字段吗?

go - 如何在循环中将 slice 用作堆栈

C++ 写时复制子串/子数组