【问题标题】:How to remove quotes from around a string in Golang如何从Golang中的字符串中删除引号
【发布时间】:2017-10-28 14:03:53
【问题描述】:

我在 Golang 中有一个用引号括起来的字符串。我的目标是删除两侧的所有引号,但忽略字符串内部的所有引号。我该怎么做呢?我的直觉告诉我要像在 C# 中那样使用 RemoveAt 函数,但我在 Go 中没有看到类似的东西。

例如:

"hello""world"

应转换为:

hello""world

为了进一步澄清,这是:

"""hello"""

会变成这样:

""hello""

因为应该只删除外部的。

【问题讨论】:

    标签: go


    【解决方案1】:

    使用slice expression

    s = s[1 : len(s)-1]
    

    如果引号可能不存在,请使用:

    if len(s) > 0 && s[0] == '"' {
        s = s[1:]
    }
    if len(s) > 0 && s[len(s)-1] == '"' {
        s = s[:len(s)-1]
    }
    

    playground example

    【讨论】:

    • 为什么len(s) 两次?为什么不这样嵌套呢?:if len(s) { if s[0] == '"' { s = s[1:] } if s[len(s)-1] == '"' { s = s[:len(s)-1] } }
    • @apokaliptis 答案会检查 len(s) 两次以处理输入 "
    • 我尝试了这两种方法来重新渲染 html 模板中的字符串,并且在这两种方法中,他们都删除了结果仍然有引号;即

      "his 是带引号但缺少第一个和最后一个字符的字符串"

    • @AlanCarlyle:看起来(a)您使用第一种方法从字符串中删除第一个和最后一个字节,无论这些字节是什么(b)模板正在添加引号。如果你还没有弄清楚你的程序出了什么问题,你应该问一个新问题。
    • @CeriseLimón 我很确定 go html/template 本身正在添加引号,因为我知道我没有将它们放在刺痛中。我一直在寻找问题的答案,并且大多数人刚刚处理了如何在 html 中转义引号以便显示。
    【解决方案2】:

    strings.Trim() 可用于从字符串中删除前导和尾随空格。如果双引号在字符串之间,它将不起作用。

    // strings.Trim() will remove all the occurrences from the left and right
    
    s := `"""hello"""`
    fmt.Println("Before Trim: " + s)                    // Before Trim: """hello"""
    fmt.Println("After Trim: " + strings.Trim(s, "\"")) // After Trim: hello
    
    // strings.Trim() will not remove any occurrences from inside the actual string
    
    s2 := `""Hello" " " "World""`
    fmt.Println("\nBefore Trim: " + s2)                  // Before Trim: ""Hello" " " "World""
    fmt.Println("After Trim: " + strings.Trim(s2, "\"")) // After Trim: Hello" " " "World
    

    游乐场链接 - https://go.dev/play/p/yLdrWH-1jCE

    【讨论】:

    • 如果我知道输入字符串的格式 Trim 会很方便。
    • 这会在开头和结尾修剪多个引号,对吗?作者只想修剪一组引号。
    【解决方案3】:

    使用slice expressions。您应该编写健壮的代码,为不完美的输入提供正确的输出。例如,

    package main
    
    import "fmt"
    
    func trimQuotes(s string) string {
        if len(s) >= 2 {
            if s[0] == '"' && s[len(s)-1] == '"' {
                return s[1 : len(s)-1]
            }
        }
        return s
    }
    
    func main() {
        tests := []string{
            `"hello""world"`,
            `"""hello"""`,
            `"`,
            `""`,
            `"""`,
            `goodbye"`,
            `"goodbye"`,
            `goodbye"`,
            `good"bye`,
        }
    
        for _, test := range tests {
            fmt.Printf("`%s` -> `%s`\n", test, trimQuotes(test))
        }
    }
    

    输出:

    `"hello""world"` -> `hello""world`
    `"""hello"""` -> `""hello""`
    `"` -> `"`
    `""` -> ``
    `"""` -> `"`
    `goodbye"` -> `goodbye"`
    `"goodbye"` -> `goodbye`
    `goodbye"` -> `goodbye"`
    `good"bye` -> `good"bye`
    

    【讨论】:

      【解决方案4】:

      您可以利用切片来删除切片的第一个和最后一个元素。

      package main
      
      import "fmt"
      
      func main() {
          str := `"hello""world"`
      
          if str[0] == '"' {
              str = str[1:]
          }
          if i := len(str)-1; str[i] == '"' {
              str = str[:i]
          }
      
          fmt.Println( str )
      }
      

      由于切片共享底层内存,因此不会复制字符串。它只是将 str 切片更改为从一个字符开始,然后更快地结束一个字符。

      这就是the various bytes.Trim functions 的工作原理。

      【讨论】:

      • @CeriseLimón 谢谢,我还在学习字符串和 []byte 之间的关系。我有一个页面解释了何时会发生副本以及何时不会发生副本,但我放错了位置。你有资源吗?
      【解决方案5】:

      使用正则表达式的单行...

      quoted = regexp.MustCompile(`^"(.*)"$`).ReplaceAllString(quoted,`$1`)
      

      但它不一定能以您可能想要的方式处理转义引号。

      The Go Playground

      翻译自here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-01
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多