如何在Golang中从字符串中删除"["字符

54

可能是一件小事情,但我却卡在这上面了一会儿...

无法从字符串中删除 "[" 字符,以下是我尝试过的方法及输出结果:

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "this[things]I would like to remove"
    t := strings.Trim(s, "[")

    fmt.Printf("%s\n", t)   
}

// output: this[things]I would like to remove

Go Playground

我也尝试了所有这些,但都没有成功:

s := "this [ things]I would like to remove"
t := strings.Trim(s, " [ ")
// output: this [ things]I would like to remove


s := "this [ things]I would like to remove"
t := strings.Trim(s, "[")
// output: this [ things]I would like to remove

没有一个有效。我在这里漏掉了什么?


4
https://golang.org/pkg/strings/#Replace - Ashwini Chaudhary
2个回答

93
您错过了阅读文档。strings.Trim()
func Trim(s string, cutset string) string

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

你输入的字符串中的字符[不是在开头也不是在结尾,而是在中间位置,所以strings.Trim()方法不会将其删除。
可以尝试使用strings.Replace()方法代替。
s := "this[things]I would like to remove"
t := strings.Replace(s, "[", "", -1)
fmt.Printf("%s\n", t)   

输出(在Go Playground上尝试):
thisthings]I would like to remove

在Go 1.12中还添加了一个strings.ReplaceAll()(基本上是 Replace(s, old, new, -1)的“简写”)函数。

不知怎么的,我错过了“前导和尾随”参数,谢谢。 - Blue Bot

-4

试试这个

   package main

   import (
       "fmt"
       "strings"
   )

   func main() {
       s := "this[things]I would like to remove"
       t := strings.Index(s, "[")

       fmt.Printf("%d\n", t)
       fmt.Printf("%s\n", s[0:t])
   }

1
这将返回第一个“[”之前的字符串,但似乎并没有回答上面的问题。当未找到“[”时,还会出现恐慌错误。 - mpx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接