doucongqian6644 2015-12-03 15:52
浏览 464

在Go中从切片中删除字符串[重复]

This question already has an answer here:

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?

</div>
  • 写回答

2条回答 默认 最新

  • dsh77114 2015-12-03 16:04
    关注

    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]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭