53

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?

icza
  • 389,944
  • 63
  • 907
  • 827
Blue Bot
  • 2,278
  • 5
  • 23
  • 33

2 Answers2

91

You are 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 is 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\n", t)   

Output (try it on the Go Playground):

thisthings]I would like to remove

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

Matt
  • 68,711
  • 7
  • 155
  • 158
icza
  • 389,944
  • 63
  • 907
  • 827
-4

Try this

   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])
   }
Rizal H.
  • 1
  • 2
  • 1
    This returns the string up to the first '[' which doesn't appear to answer the question above. There is also a panic bug when '[' isn't found. – mpx Apr 16 '22 at 14:37