Parry Wang
Parry Wang

Reputation: 115

Question about indexing characters of strings

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?

Upvotes: 0

Views: 227

Answers (2)

Gopher
Gopher

Reputation: 751

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

Upvotes: 1

mkopriva
mkopriva

Reputation: 38213

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.

Upvotes: 3

Related Questions