如何从 Golang 中的字符串 Trim "[" char

How to Trim "[" char from a string in Golang

可能是一件愚蠢的事情,但我坚持了一会儿...

不能 trim 来自字符串的 "[" 字符,我尝试输出的东西:

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

None 有效。我在这里错过了什么?

您没有阅读文档。 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) 的 "shorthand")。

试试这个

   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])
   }