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

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

Question about indexing characters of strings

问题

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

package main

import "fmt"

func main() {
    vendor1 := "Cisco"
    fmt.Println(vendor1[0])
    fmt.Println(vendor1[1:4])
    fmt.Println(vendor1[1:])
    fmt.Println(vendor1[:])
}

输出结果:

C:\Golang\VARIABLE> go run .\variable.go
67
isc
isco
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:

package main

import "fmt"

func main() {
	vendor1 := "Cisco"
	fmt.Println(vendor1[0])  
	fmt.Println(vendor1[1:4]) 
	fmt.Println(vendor1[1:])  
	fmt.Println(vendor1[:])
}

Output:

C:\Golang\VARIABLE> go run .\variable.go
67
isc
isco
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,因为它们是字符串。我修改了您的代码如下:

package main

import (
	"fmt"
)

func main() {

	vendor1 := "Cisco"

	fmt.Printf("%c\n", vendor1[0])

	fmt.Printf("%s\n", vendor1[1:4])
	fmt.Printf("%s\n", vendor1[1:])
	fmt.Printf("%s\n", vendor1[:])

}

输出:

C
isc
isco
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:

package main

import (
	"fmt"
)

func main() {

	vendor1 := "Cisco"

	fmt.Printf("%c\n", vendor1[0])

	fmt.Printf("%s\n", vendor1[1:4])
	fmt.Printf("%s\n", vendor1[1:])
	fmt.Printf("%s\n", vendor1[:])

}

Output:

C
isc
isco
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:

确定