如何在 Golang 中修剪字符串中的“[”字符

问题描述 投票:0回答:2

可能是一件愚蠢的事情,但被卡住了一段时间......

无法从字符串中修剪

"["
字符,我在输出中尝试过的事情:

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

去游乐场

还尝试了所有这些,但没有成功:

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

没有一个起作用。我在这里缺少什么?

string go trim
2个回答
90
投票

您错过了阅读文档。

strings.Trim()

func Trim(s string, cutset string) string

Trim 返回字符串 s 的切片,其中删除了切割集中包含的所有 前导和尾随 Unicode 代码点。

输入中的

[
字符既不在 leading 也不在 trailing 位置,它位于 middle,因此
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)
的“简写”)。


-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])
   }
© www.soinside.com 2019 - 2024. All rights reserved.