如何从Golang中的字符串中删除引号

Ram*_*unt 10 go

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

例如:

"hello""world"
Run Code Online (Sandbox Code Playgroud)

应转换为:

hello""world
Run Code Online (Sandbox Code Playgroud)

为进一步澄清,这:

"""hello"""
Run Code Online (Sandbox Code Playgroud)

会成为这样的:

""hello""
Run Code Online (Sandbox Code Playgroud)

因为外面的应该只删除.

Cer*_*món 24

使用切片表达式:

s = s[1 : len(s)-1]
Run Code Online (Sandbox Code Playgroud)

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

if len(s) > 0 && s[0] == '"' {
    s = s[1:]
}
if len(s) > 0 && s[len(s)-1] == '"' {
    s = s[:len(s)-1]
}
Run Code Online (Sandbox Code Playgroud)

操场的例子


Rah*_*tal 6

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

package main

import (
    "fmt"
    "strings"
)

func main() {

    // strings.Trim() will work in this case
    
    s := `"hello"`
    fmt.Println("Without trim: " + s)               // Without trim: "  hello"
    fmt.Println("Trim double quotes: " + strings.Trim(s, "\"")) // Trim double quotes:   hello
    
    
    // strings.Trim() will not work in this case
    
    s2 := `"Hello" "World"`
    fmt.Println("Without trim: " + s2)              // Without trim: "  hello"
    fmt.Println("Trim double quotes: " + strings.Trim(s2, "\""))    // Trim double quotes:   hello
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接 - https://play.golang.org/p/x_DG9vHvzY

  • 这会修剪开头和结尾的多个引号,对吗?作者只想删除一组引号。 (2认同)