How to get character in string golang?
May 03, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
Today, we are going to get characters from a string in golang, here we will use basic built-in syntax to get a char from a string.
To get char from a string, you have to use the string()
method, and pass your string as a parameter with your char index.
Take an example.
You have a hello
string and if you want get their second char then you have to write like the below example.
string("Hello"[1])
Let check with complete example.
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
}
You will get index char in your golang console, let check the output.
Let’s see actual output of the code.
All the best 👍