dongpan9760 2016-11-23 09:28
浏览 137
已采纳

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

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
", 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?

  • 写回答

1条回答 默认 最新

  • duankuiyuant3940 2016-11-23 09:38
    关注

    You're missing reading the doc. 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.

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

    Try strings.Replace() instead:

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

    Output (try it on the 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)).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭