Split a String in Golang

In Go, you can split a string into substrings using the strings.Split() function from the strings package. This function takes two arguments: the string you want to split and the separator used to determine where to split the string.

Here’s how you can split a string using strings.Split():

package main

import (

func main() {
	message := "apple,banana,cherry,grape"
	// Splitting the string using the comma separator
	fruits := strings.Split(message, ",")

	// Printing the resulting substrings
	fmt.Println("Fruits:", fruits)

Output :

Fruits: [apple banana cherry grape]

In this example, we import the strings package and create a string message containing comma-separated values. We use the strings.Split() function to split the string into substrings using the comma as the separator. The result is a slice of strings, where each element represents a substring.

You can use any character or substring as the separator, not just a single character. For example:

date := "2023-07-29"
dateParts := strings.Split(date, "-")
fmt.Println("Year:", dateParts[0], "Month:", dateParts[1], "Day:", dateParts[2])

Output :

Year: 2023 Month: 07 Day: 29

Remember that strings.Split() returns a slice of strings, and each element represents a substring created by splitting the original string based on the provided separator.