Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

trim

go

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?

like image 484
Blue Bot Avatar asked Nov 23 '16 09:11

Blue Bot


People also ask

How do I remove a character from a string in go?

Trim() method. It accepts the original string and the characters to be removed as its arguments. fmt. Println(strings.

How do I trim a string in Golang?

res1 := strings. Trim(str1, "!" ) 2. TrimLeft: This function is used to trim the left-hand side(specified in the function) Unicode code points of the string.

How do I remove special characters from a string in Golang?

The strings package of Golang has a Replace() function which we can use to replace some characters in a string with a new value. It replaces only a specified "n" occurrences of the substring.

How do you remove spaces from a string in Golang?

To remove all spaces from a string in Go language, we may replace all the spaces with an empty string. To replace the white spaces with empty string, we can use strings. ReplaceAll() function.


1 Answers

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)).

like image 174
icza Avatar answered Oct 18 '22 06:10

icza