Home » How to Split String into Two Variables in Golang

How to Split String into Two Variables in Golang

Use strings.Split() function to split a string into substrings and assign them to two variables in Golang.

The Split method takes the separator as an argument to break the string into slices of substrings and return a string array.

Use the index to access the element from the array and assign them to variables in golang.

In this article, we will discuss how to use Split() in Golang to split a string and assign it to two variables.

Golang Split String and Assign to Multiple Variables

Golang string package has a built-in Split() function that takes two arguments; a string to split into and a separator to break the string into a slice of substrings.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Declare a string
	s1 := "10.0.0.1:1020"

	// Use Split() function to split the string by colon (:)

	tempstr := strings.Split(s1, ":")

	// use array index to get the element

	ip, port := tempstr[0], tempstr[1]

	// Print the varaibles
	fmt.Println("IP Address:", ip)
	fmt.Println("Port:", port)

}

In the above Golang program, we have used strings.Split() function to split the string into a string array.

To split a string and assign it to two variables, follow the below steps

  1. Declare a string and store it in a variable s1
  2. Use the Split function to split a string by colon (:) and store the result in the tempstr variable. e.g. strings.Split(s1,”:”)
  3. The Split function splits a string into a string array.
  4. Use the index to access the values at 0 and 1 index. e.g. tempstr[0] tempstr[1]
  5. Assign the values to two comma-separated variables, ip,port:= tempstr[0],tempstr[1]
  6. Use fmt.Println to print the variable.

The output of the above golang program to split a string into two variables is:

IP Address: 10.0.0.1
Port: 1020

Cool Tip: How to split a string to get the last element in Golang!

Conclusion

I hope the above article on how to use the Golang Split() function to split a string into two variables is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment