Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trim whitespaces in Go from a slice after Split

Tags:

go

I have a string that is comma separated, so it could be test1, test2, test3 or test1,test2,test3 or test1, test2, test3.

I split this in Go currently with strings.Split(s, ","), but now I have a []string that can contain elements with an arbitrary numbers of whitespaces.

How can I easily trim them off? What is best practice here?

This is my current code

var property= os.Getenv(env.templateDirectories)
if property != "" {
    var dirs = strings.Split(property, ",")
    for index,ele := range dirs {
        dirs[index] = strings.TrimSpace(ele)
    }
    return dirs
}

I come from Java and assumed that there is a map/reduce etc functionality in Go also, therefore the question.

like image 242
Emerson Cod Avatar asked Mar 22 '18 12:03

Emerson Cod


People also ask

How do you trim spaces in go?

To trim spaces around string in Go language, call TrimSpace function of strings package, and pass the string as argument to it. TrimSpace function returns a String.

How do you remove spaces in Split?

To split the sentences by comma, use split(). For removing surrounding spaces, use trim().

Does string split remove whitespace?

Split method, which is not to trim white-space characters and to include empty substrings.


1 Answers

You can use strings.TrimSpace in a loop. If you want to preserve order too, the indexes can be used rather than values as the loop parameters:

Go Playground Example

EDIT: To see the code without the click:

package main

import (
    "fmt"
    "strings"
)

func main() {
    input := "test1,          test2,  test3"
    slc := strings.Split(input , ",")
    for i := range slc {
      slc[i] = strings.TrimSpace(slc[i])
    }
    fmt.Println(slc)
}
like image 162
vahdet Avatar answered Nov 16 '22 01:11

vahdet