Home >Backend Development >Golang >What are the methods to convert string to array in Go language?
Go language, as a very popular programming language, provides many convenient methods when processing conversions between strings and arrays. Below we will introduce some commonly used methods, including specific code examples.
package main import ( "fmt" "strings" ) func main() { str := "apple,orange,banana" arr := strings.Split(str, ",") fmt.Println(arr) }
package main import ( "fmt" "strconv" ) func main() { str := "1 2 3 4 5" splitStr := strings.Fields(str) arr := make([]int, len(splitStr)) for i, s := range splitStr { num, err := strconv.Atoi(s) if err != nil { panic(err) } arr[i] = num } fmt.Println(arr) }
The above are two common ways to convert strings into arrays Method, choose the appropriate method for conversion according to actual needs. These methods are not only simple and easy to understand, but also perform well and are suitable for many scenarios. I hope these examples can help you better understand the method of converting string to array in Go language.
The above is the detailed content of What are the methods to convert string to array in Go language?. For more information, please follow other related articles on the PHP Chinese website!