go string to int array with space separator
Converting a Go String to an Int Array with Space Separator
To convert a Go string to an int array with a space separator, you can follow these steps:
- Split the String by Space:
- Use the
strings.Split
function to split the string into individual elements based on the space separator. Example:
go str := "10 20 30 40" arr := strings.Split(str, " ")
Convert String Elements to Integers:
- Iterate through the array of string elements and convert each element to an integer using the
strconv.Atoi
function. Example:
go var intArr []int for _, v := range arr { num, err := strconv.Atoi(v) if err == nil { intArr = append(intArr, num) } }
Complete Code Example:
Here's a complete example of how to achieve this in Go: ```go package main
import ( "fmt" "strconv" "strings" )
func main() { str := "10 20 30 40" arr := strings.Split(str, " ")
var intArr []int for _, v := range arr { num, err := strconv.Atoi(v) if err == nil { intArr = append(intArr, num) } } fmt.Println(intArr) // Output: [10 20 30 40]
} ```
By following these steps, you can effectively convert a Go string to an int array with a space separator.
[[SOURCE 6]]