doushun1904 2018-01-25 18:01
浏览 1668
已采纳

删除Golang中的双引号或单引号

Shouldn't strconv.Unquote handle both single and double quotes?

See also https://golang.org/src/strconv/quote.go - line 350

However following code returns a syntax error:

s, err := strconv.Unquote(`'test'`)
if err != nil {
  fmt.Println(err)
} else {
  fmt.Println(s)
}

https://play.golang.org/p/TnprqhNdwD1

But double quotes work as expected:

s, err := strconv.Unquote(`"test"`)
if err != nil {
  fmt.Println(err)
} else {
  fmt.Println(s)
}

What am I missing?

  • 写回答

3条回答 默认 最新

  • doujingqu3030 2018-01-25 21:05
    关注

    There is no ready function for what you want in the standard library.

    What you presented works, but we can make it simpler (and likely more efficient):

    func trimQuotes(s string) string {
        if len(s) >= 2 {
            if c := s[len(s)-1]; s[0] == c && (c == '"' || c == '\'') {
                return s[1 : len(s)-1]
            }
        }
        return s
    }
    

    Testing it:

    fmt.Println(trimQuotes(`'test'`))
    fmt.Println(trimQuotes(`"test"`))
    fmt.Println(trimQuotes(`"'test`))
    

    Output (try it on the Go Playground):

    test
    test
    "'test
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导