获取字符串中指定索引位置的字符。

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

Get character at index of string

问题

为什么我会得到错误信息 cannot use s[0] (type byte) as type string in assignment?据我所知,s 是一个 string 类型,为什么访问一个字符后它会变成 byte 类型?

英文:
func lengthOfLongestSubstring(s string) {
	match := make(map[string]int)
	var current string

	current = s[0]

	if match[current] == 1 {
		///
	}

}

Why do I get the error cannot use s[0] (type byte) as type string in assignment? As far as I can tell it's clear that s is of type string, why does accessing a character turn it into type byte?

答案1

得分: 6

func lengthOfLongestSubstring(s string) {
strArr := []rune(s)
fmt.Println(string(strArr[0]))
}

英文:
func lengthOfLongestSubstring(s string) {
    strArr:=[]rune(s) 
    fmt.Println(string(strArr[0]))

}

答案2

得分: 5

让我们阅读一下Go语言设计师之一对于Go中字符串的看法(Go中的字符串):

在Go中,字符串实际上是一个只读的字节切片。如果你对字节切片是什么或者它是如何工作的有任何疑问,请阅读前面的博文;我们在这里假设你已经了解了。

首先要明确的是,字符串可以包含任意字节。它不需要保存Unicode文本、UTF-8文本或任何其他预定义格式。就字符串的内容而言,它与字节切片完全等价。

所以,在你的情况下,s[0]是一个字节类型,如果你确实需要赋值,你需要进行显式的类型转换。

英文:

Let's read how one of the Go designers look at strings in go:

> In Go, a string is in effect a read-only slice of bytes. If you're at all uncertain about what a slice of bytes is or how it works, please read the previous blog post; we'll assume here that you have.
>
> It's important to state right up front that a string holds arbitrary bytes. It is not required to hold Unicode text, UTF-8 text, or any other predefined format. As far as the content of a string is concerned, it is exactly equivalent to a slice of bytes.

So, apparently in your case, s[0] is a byte type, you need explicit case if you really need the assignment.

huangapple
  • 本文由 发表于 2017年6月15日 23:43:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/44571744.html
匿名

发表评论

匿名网友

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

确定