-3

I have a string that may or may not be surrounded with double quotes or single quotes. I want to remove the first set of quotes, if present. So:

"foo" --> foo
""foo"" --> "foo"
'foo' --> foo
'foo --> foo

Etc.

I found this answer, which describes using a slice expression to index into the first and last characters of the string, then grab a slice of the string if either character is a quote. So I tried to tweak the code to cover both single and double quotes:

func stripQuotes(str string) string {
    s := str[:]
    if len(s) > 0 && (s[0] == '"' || s[0] == "'") {
        s = s[1:]
    }
    if len(s) > 0 && (s[len(s)-1] == '"' || s[len(s)-1] == "'") {
        s = s[:len(s)-1]
    }

    return s
}

But it returns an error:

cannot convert "'" (type untyped string) to type byte

So I tried converting the single quote to a byte, but that didn't work either:

...
if len(s) > 0 && (s[0] == '"' || s[0] == byte("'")) {
...

It returns the error:

cannot convert "'" (type untyped string) to type byte

I know that there's some basic string handling knowledge I'm missing here, but I'm not sure what. Is there a simple way to identify single quotes in a string?

Lou
  • 2,200
  • 2
  • 33
  • 66
  • "This question is not reproducible or was caused by typos" - Okay. Nobody has said that they've tried and failed to reproduce it, and the error is definitely reproducible in the Go playground: https://play.golang.org/p/QJbLjC2gib9. The error was not caused by a typo if it's down to me not understanding how a feature of the language works - if that's the case then every SO question should be closed for this reason. Anyone care to explain this further? – Lou Jun 05 '21 at 12:39
  • When closing a question the clarifying text says "While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers." Syntax errors are easily solved using existing resources on the web and don't create new knowledge, so many don't consider these questions appropriate for SO. You don't have to agree with this. Don't read anything into this. Votes about the fitness of a question for SO, not the validity, source, or merit of a problem. – Peter Jun 05 '21 at 13:52

1 Answers1

7

In Go, double quotes denote string literals and single quotes denote rune or byte literals. They are not interchangeable like in other languages.

A literal single quote is therefore spelled '\''.

Peter
  • 29,454
  • 5
  • 48
  • 60
  • Thanks, this has fixed the issue! I'm not sure why the question was closed but I've got working code now in any case. – Lou Jun 05 '21 at 12:39