【问题标题】:How to add single-quotes to strings in Golang?如何在 Golang 中为字符串添加单引号?
【发布时间】:2020-09-08 22:57:11
【问题描述】:

也许这是一个简单的问题,但我还没有弄清楚如何做到这一点:

我在 Go 中有一个字符串切片,我想将其表示为逗号分隔的字符串。这是切片example:

example := []string{"apple", "Bear", "kitty"}

我想将其表示为一个带单引号的逗号分隔字符串,即

'apple', 'Bear', 'kitty'

我不知道如何在 Go 中有效地做到这一点。

例如,strings.Join() 给出一个逗号分隔的字符串:

commaSep := strings.Join(example, ", ")
fmt.Println(commaSep)
// outputs: apple, Bear, kitty

关闭,但不是我需要的。我也知道如何使用strconv 添加双引号,即

new := []string{}
for _, v := range foobar{
    v = strconv.Quote(v)
    new = append(new, v)

}
commaSepNew := strings.Join(new, ", ")
fmt.Println(commaSepNew)
// outputs: "apple", "Bear", "kitty"

再一次,不是我想要的。

如何输出字符串'apple', 'Bear', 'kitty'?

【问题讨论】:

  • 使用new 作为变量名是个坏主意。 new() 也是 allocation 函数。

标签: string go quotes strconv


【解决方案1】:

下面的代码怎么样?

commaSep := "'" + strings.Join(example, "', '") + "'"

Go Playground

【讨论】:

  • 此操作失败,切片为空:play.golang.org/p/C_KPKZAUm1e
  • 解决方案:if len(example) > 0 { /* above code */ }。虽然 OP 实际上并没有说明如果切片为空,什么是正确的输出。
  • 我认为如果切片为空,则通过。因此,上述条件将起作用。
  • 感谢您的帮助!我在想这样的事情,但认为也许有一个“更好的方法”---我肯定会使用这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2018-11-28
  • 2011-05-24
  • 2021-11-11
相关资源
最近更新 更多