go - 拆分后如何从 slice 中修剪 Go 中的空格

标签 go

我有一个逗号分隔的字符串,所以它可能是 test1, test2, test3test1,test2,test3test1, test2, test3

我目前在 Go 中使用 strings.Split(s, ",") 拆分它,但现在我有一个 []string 可以包含任意元素空格数。

如何轻松剪掉它们?这里的最佳做法是什么?

这是我当前的代码

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
}

我来自 Java,并假设 Go 中也有 map/reduce 等功能,因此出现了这个问题。

最佳答案

您可以在循环中使用 strings.TrimSpace。如果你也想保留顺序,可以使用索引而不是值作为循环参数:

Go Playground Example

编辑:无需点击即可查看代码:

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

关于go - 拆分后如何从 slice 中修剪 Go 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49429269/

相关文章:

戈朗 : Parse all templates in directory and subdirectories?

Go 1.0.2 zlib 压缩时如何提高速度

http - 将 mux.Walk 的结果发送到 ResponseWriter

go - 如何关闭所有 "asleep"的 goroutines?

unit-testing - testify/assert.Contains 如何与 map 一起使用?

amazon-web-services - 使用 golang 的 http.ResponseWriter 进行 AWS S3 大文件反向代理

go - 在 sync.Map 中加载或存储而无需每次都创建新结构

go - golang的 "defer"怎么捕获闭包的参数?

postgresql - 微服务使 postgres 连接倍增

function - 在 Go 中是否可以调用带有命名参数的函数?