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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40760490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:35:22  来源:igfitidea点击:

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

stringgotrim

提问by Blue Bot

Probably a silly thing but got stuck on it for a bit...

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

Can't trim a "["char from a string, things I tried with outputs:

无法"["从字符串中修剪字符,我尝试输出的内容:

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

去游乐场

Also tried all of those, with no success:

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

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 worked. What am I missing here?

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

回答by icza

You're missing reading the doc. strings.Trim():

你错过了阅读文档。strings.Trim()

func Trim(s string, cutset string) string

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

func Trim(s string, cutset string) string

Trim 返回包含在 cutset 中的所有前导和尾随Unicode 代码点的字符串 s 的切片。

The [character in your input is not in a leadingnor in a trailingposition, it's in the middle, so strings.Trim()–being well behavior– will not remove it.

[你输入的字符不是一个领导也不在尾部的位置,它在中间,所以strings.Trim()-being以及动作-将无法将其删除。

Try strings.Replace()instead:

试试吧strings.Replace()

s := "this[things]I would like to remove"
t := strings.Replace(s, "[", "", -1)
fmt.Printf("%s\n", t)   

Output (try it on the Go Playground):

输出(在Go Playground上试试):

thisthings]I would like to remove

There's also a strings.ReplaceAll()added in Go 1.12 (which is basically a "shorthand" for Replace(s, old, new, -1)).

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