关于索引字符串字符的问题

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

Question about indexing characters of strings

问题

下面是我创建的程序,用于理解在Go语言中如何对字符串字符进行索引:

  1. package main
  2. import "fmt"
  3. func main() {
  4. vendor1 := "Cisco"
  5. fmt.Println(vendor1[0])
  6. fmt.Println(vendor1[1:4])
  7. fmt.Println(vendor1[1:])
  8. fmt.Println(vendor1[:])
  9. }

输出结果:

  1. C:\Golang\VARIABLE> go run .\variable.go
  2. 67
  3. isc
  4. isco
  5. Cisco

让我感到困惑的是,Println(vendor1[0]) 返回的是数字 67 而不是 C,为什么会这样?为什么它与 Println(vendor1[1:4])Println(vendor1[1:])Println(vendor1[:]) 返回的期望字符不同?

英文:

Below is the program I created to understand how indexing of string characters work in Go:

  1. package main
  2. import "fmt"
  3. func main() {
  4. vendor1 := "Cisco"
  5. fmt.Println(vendor1[0])
  6. fmt.Println(vendor1[1:4])
  7. fmt.Println(vendor1[1:])
  8. fmt.Println(vendor1[:])
  9. }

Output:

  1. C:\Golang\VARIABLE> go run .\variable.go
  2. 67
  3. isc
  4. isco
  5. Cisco

What puzzled me is that Println(vendor1[0]) returns the number '67' instead of 'C', why is that so? Why it is different from Println(vendor1[1:4]) , Println(vendor1[1:]) and Println(vendor1[:]) which all return the desired characters?

答案1

得分: 3

Index expressions(索引表达式)与slice expressions(切片表达式)不是同一回事,请不要混淆它们。

索引操作返回的是一个byte类型,它是uint8的类型别名,而Println函数只是简单地打印出这个无符号整数。

切片操作返回的是一个字符串,这就是为什么Println输出的是文本。

英文:

Index expressions are not the same thing as slice expressions, don't conflate them.

Indexing, as opposed to slicing, returns a byte which is a type alias of uint8, and Println simply prints out the unsigned integer.

Slicing returns a string, which is why Println outputs a text.

答案2

得分: 1

要打印索引为0的值,请改用fmt.Printf("%c\n", vendor1[0])而不是fmt.Println(vendor1[0]),对于其他三个值,您可以使用fmt.Printf()%s,因为它们是字符串。我修改了您的代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. vendor1 := "Cisco"
  7. fmt.Printf("%c\n", vendor1[0])
  8. fmt.Printf("%s\n", vendor1[1:4])
  9. fmt.Printf("%s\n", vendor1[1:])
  10. fmt.Printf("%s\n", vendor1[:])
  11. }

输出:

  1. C
  2. isc
  3. isco
  4. Cisco
英文:

To print the value at index 0 use fmt.Printf("%c\n", vendor1[0]) instead of fmt.Println(vendor1[0]),for the other three values you can use %s with fmt.Printf() since they are string.I modified your code as follows:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. vendor1 := "Cisco"
  7. fmt.Printf("%c\n", vendor1[0])
  8. fmt.Printf("%s\n", vendor1[1:4])
  9. fmt.Printf("%s\n", vendor1[1:])
  10. fmt.Printf("%s\n", vendor1[:])
  11. }

Output:

  1. C
  2. isc
  3. isco
  4. Cisco

huangapple
  • 本文由 发表于 2021年8月22日 21:02:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/68881582.html
匿名

发表评论

匿名网友

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

确定