How to remove quotes from a string in the Golang

I have a string in the Golang that is surrounded by quotation marks. My goal is to remove all quotation marks around the sides, but ignore all quotation marks inside the string. How should I do it? My instinct tells me to use the RemoveAt function, as in C #, but I don't see anything like it in Go.

For instance:

"hello""world"

should be converted to:

hello""world

For further clarification, this is:

"""hello"""

will be as follows:

""hello""

because external ones should be deleted ONLY.

+4
source share
3 answers

Use the slice expression :

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

If it is likely that there are no quotes, 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

+16
source

You can use slices to remove the first and last element of a 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 )
}

, . str, , .

bytes.Trim.

+2

Use slice expressions . You must write reliable code that provides the correct output for imperfect input. For instance,

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

Conclusion:

`"hello""world"` -> `hello""world`
`"""hello"""` -> `""hello""`
`"` -> `"`
`""` -> ``
`"""` -> `"`
`goodbye"` -> `goodbye"`
`"goodbye"` -> `goodbye`
`goodbye"` -> `goodbye"`
`good"bye` -> `good"bye`
+2
source

Source: https://habr.com/ru/post/1678053/


All Articles