split a string into two strings in go

You can split a string into two parts in Go by using the strings package's Split function. The Split function takes three arguments: the string to split, the separator to use, and the maximum number of splits to perform. If you only want to split the string into two parts, you can pass in a 1 for the maximum number of splits to perform.

main.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	//string to be splitted
	str := "This is a sample string"

	//splitting string using the space delimiter, into 2 parts
	splitArr := strings.Split(str, " ")
	//first string
	first := splitArr[0]
	//second string
	second := splitArr[1]

	fmt.Println("First split string: ", first)
	fmt.Println("Second split string: ", second)
}
386 chars
22 lines

Output:

main.go
First split string: This
Second split string: is
49 chars
3 lines

gistlibby LogSnag