Home > Backend Development > Golang > What are the methods to convert string to array in Go language?

What are the methods to convert string to array in Go language?

WBOY
Release: 2024-03-12 14:15:03
Original
950 people have browsed it

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.

Method 1: Use the Split method of the strings package

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "apple,orange,banana"
    arr := strings.Split(str, ",")
    
    fmt.Println(arr)
}
Copy after login

Method 2: Use the Split method of the strconv package

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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template