从字符串中删除单引号 – “无法将 ‘(未指定类型的字符串)’ 用作字节类型”

huangapple go评论104阅读模式
英文:

Removing single quotes from a string - "Cannot use "'" (type untyped string) as type byte"

问题

我有一个字符串,可能被双引号或单引号包围。如果存在的话,我想要去掉第一对引号。所以:

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

等等。

我找到了这个答案,它描述了使用切片表达式来索引字符串的第一个和最后一个字符,然后如果任一字符是引号,就获取字符串的一个切片。所以我尝试修改代码来处理单引号和双引号:

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
}

但是它返回一个错误:

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

所以我尝试将单引号转换为字节,但也不起作用:

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

它返回错误:

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

我知道我在这里缺少一些基本的字符串处理知识,但我不确定是什么。有没有一种简单的方法来识别字符串中的单引号?

英文:

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?

答案1

得分: 7

在Go语言中,双引号表示字符串字面量,单引号表示rune或byte字面量。它们不像其他语言中可以互换使用。

因此,一个单引号的字面量应该写作'\''

英文:

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 '\''.

huangapple
  • 本文由 发表于 2021年6月4日 17:21:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/67834731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定