可能是一件愚蠢的事情,但被卡住了一段时间......
无法从字符串中修剪
"["
字符,我在输出中尝试过的事情:
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
没有一个起作用。我在这里缺少什么?
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
strings.ReplaceAll()
(这基本上是 Replace(s, old, new, -1)
的“简写”)。
试试这个
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])
}