[英]How to Trim “[” char from a string in Golang
可能是一件愚蠢的事情,但被卡住了一段时间......
无法从字符串中修剪"["
字符,我尝试输出的内容:
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 返回包含在 cutset 中的所有前导和尾随Unicode 代码点的字符串 s 的切片。
输入中的[
字符既不在前导位置也不在尾随位置,而是在中间,因此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)
的“简写”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.