Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index characters in a Golang string?

People also ask

Can you index strings Golang?

Golang String Index() is a built-in function that returns the index of the first instance of substr in s, or -1 if substr is not present in the string. The Index() function is used to find the index value of the first instance of the given string from the original string.

How do you index a character in a string?

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string: String anotherPalindrome = "Niagara.

How do you get a character from a string in Go?

To access the string's first character, we can use the slice expression [] in Go. In the example above, we have passed [0:1] to the slice expression. so it starts the extraction at position 0 and ends at position 1 (which is excluded). Note: The above syntax works on ASCII Characters.


Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))              // ASCII only
    fmt.Println(string([]rune("Hello, 世界")[1])) // UTF-8
    fmt.Println(string([]rune("Hello, 世界")[8])) // UTF-8
}

Output:

e
e
界

Read:

Go Programming Language Specification section on Conversions.

The Go Blog: Strings, bytes, runes and characters in Go


How about this?

fmt.Printf("%c","HELLO"[1])

As Peter points out, to allow for more than just ASCII:

fmt.Printf("%c", []rune("HELLO")[1])

Can be done via slicing too

package main

import "fmt"

func main() {
    fmt.Print("HELLO"[1:2])
}

NOTE: This solution only works for ASCII characters.


You can also try typecasting it with string.

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))
}

Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x). The %c format specification works for any integer type.