gpt4 book ai didi

string - 如何从 Golang 中的字符串中修剪 "["字符

转载 作者:IT老高 更新时间:2023-10-28 13:05:01 25 4
gpt4 key购买 nike

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

无法从字符串中修剪 "[" 字符,我尝试使用输出:

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

没有工作。我在这里错过了什么?

最佳答案

您错过了阅读文档。 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

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

关于string - 如何从 Golang 中的字符串中修剪 "["字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com