How to convert string to array in Go language?

WBOY
Release: 2024-03-12 21:09:04
Original
956 people have browsed it

How to convert string to array in Go language?

Converting a string to an array is a common operation in programming, especially when processing data. In Go language, we can use the built-in strings package to achieve this function. Below I will provide you with a concrete code example to demonstrate how to convert a string to an array in Go language:

package main

import (
    "fmt"
    "strings"
)

func main() {
    // 定义一个字符串
    str := "apple,banana,orange,grape"

    // 使用strings包的Split函数将字符串按照逗号分割成数组
    arr := strings.Split(str, ",")

    // 遍历数组并打印每个元素
    for _, value := range arr {
        fmt.Println(value)
    }
}
Copy after login

In this example, we first define a string str, which contains four fruit names, each separated by commas. Then we use the strings.Split function to split this string into a string array arr according to commas. Finally, we use for to loop through the array and print out each element one by one.

Through this example, you can understand how to convert a string into an array in Go language, and you can extend and adjust the code according to specific needs. Hope this example helps you!

The above is the detailed content of How to convert string to array in Go language?. For more information, please follow other related articles on the PHP Chinese website!

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