dongyigua4468
2017-05-27 23:46
浏览 698
已采纳

如何在Golang中删除字符串周围的引号

I have a string in Golang that is surrounded by quote marks. My goal is to remove all quote marks on the sides, but to ignore all quote marks in the interior of the string. How should I go about doing this? My instinct tells me to use a RemoveAt function like in C#, but I don't see anything like that in Go.

For instance:

"hello""world"

should be converted to:

hello""world

For further clarification, this:

"""hello"""

would become this:

""hello""

because the outer ones should be removed ONLY.

图片转代码服务由CSDN问答提供 功能建议

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

例如:

  “ hello”“ world” 
   
 
 

应转换为:

  hello“” world \  n   
 
 

为进一步说明,

 “”“” hello“”“ 
  <  / pre> 
 
 

会变成这样:

 “” hello“” 
   
 
 

因为外面的东西只能去除。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanlu0075 2017-05-27 23:56
    已采纳

    Use a slice expression:

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

    If there's a possibility that the quotes are not present, then use this:

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

    playground example

    打赏 评论
  • dth34653 2017-05-28 00:05

    You can take advantage of slices to remove the first and last element of the slice.

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

    Since a slice shares the underlying memory, this does not copy the string. It just changes the str slice to start one character over, and end one character sooner.

    This is how the various bytes.Trim functions work.

    打赏 评论
  • dongleiwei2182 2017-05-28 01:03

    Use slice expressions. You should write robust code that provides correct output for imperfect input. For example,

    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`
    ", test, trimQuotes(test))
        }
    }
    

    Output:

    `"hello""world"` -> `hello""world`
    `"""hello"""` -> `""hello""`
    `"` -> `"`
    `""` -> ``
    `"""` -> `"`
    `goodbye"` -> `goodbye"`
    `"goodbye"` -> `goodbye`
    `goodbye"` -> `goodbye"`
    `good"bye` -> `good"bye`
    
    打赏 评论

相关推荐 更多相似问题