how to convert string to array in golang?
September 14, 2022Hi Friends đź‘‹,
Welcome To aGuideHub! ❤️
To convert string to array in golang, just use []string
and assign your value it will convert string to array. Only you have to pass string into an array.
Here, we will also see convert string to array and access each char of string.
Follow the below tutorial if you are struggling with installing GO in windows.
https://aguidehub.com/blog/how-to-install-golang-in-windows/
Today, I will show you how do I convert string to array in golang, as above mentioned I’m going to use []string
way.
Let’s start our Golang convert string to array example
Convert whole string into an array example
main.go
package main
import "fmt"
func main() {
s:= "infinitbility"
a:= []string{s}
fmt.Println(a)
}
In the above example, we have converted string to array and printed in golang console. let’s check the output.
Output
[infinitbility]
Convert string to array and access each char example
main.go
package main
func main() {
str := "infinitbility"
chars := []rune(str)
for i := 0; i < len(chars); i++ {
char := string(chars[i])
println(char)
}
}
In the above example, we have converted string into an array and printed each element of array in golang console. let’s check the output.
Output
i
n
f
i
n
i
t
b
i
l
i
t
y
I hope it helps you, All the best 👍.