Split a string and assign it to variables GO? [SOLVED]


GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

In the previous post, I already introduced some methods to split a string in Golang. But the question is how we can assign the result after splitting the string to another variable. We are going to answer it today with some detailed examples.

 

Example 1: Split a string with strings.Split() function

func Split(s, sep string) []string: Split slices s into all substrings separated by sep and return a slice of the substrings between those separators. If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s. If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

We can see that the return value of this function is a string slice. We can create a slice and assign it as the return value of the Split() function:

package main

import (
	"fmt"
	"strings"
)

func main() {
	var result []string

	// split by space character
	result = strings.Split("this is a split string example", " ")

	fmt.Println(len(result))
	fmt.Println("first element:", result[0])
	fmt.Printf("type of result: %T\n", result)
}

 

Example 2: Split by whitespace or newline using Fields() function

func Fields(s string) []string: Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.

The below code shows how to use Fields() function to split a string by whitespace or newline then assign the return value to a string slice

package main

import (
	"fmt"
	"strings"
)

func main() {
	var result []string

	// split by space character
	result = strings.Fields(" \t \n this is \t split example \n \t  ")

	fmt.Println(len(result))
	fmt.Println("first element:", result[0])
	fmt.Printf("type of result: %T\n", result)
}

Output:

4
first element: this
type of result: []string

We can see that split functions usually return a string slice that contains all the elements after splitting. We can call the split functions and then assign the return value to a string array.

 

Example 3: Split an IP address by the SplitHostPort() function

For some special cases such as splitting an IP address, we can use the net.SplitHostPort() function to get the result:

func SplitHostPort(hostport string) (host, port string, err error): SplitHostPort splits a network address of the form "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port" into host or host%zone and port. A literal IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".

You can see this function returns three variables: the host, the port, and the error. In the example below, we will try to analyze an IP address by calling the SplitHostPort() function:

package main

import (
	"fmt"
	"net"
)

func main() {
	host, port, err := net.SplitHostPort("127.0.0.1:8080")
	if err == nil {
		fmt.Println("The host:", host, " The port:", port, " Erorr:", err)
	} else {
		fmt.Println(err)
	}

	host2, port2, err2 := net.SplitHostPort("ACKSEWW8080")
	if err2 == nil {
		fmt.Println("The host:", host2, " The port:", port2, " Erorr:", err2)
	} else {
		fmt.Println(err2)
	}

}

Output:

The host: 127.0.0.1  The port: 8080  Erorr: <nil>
address ACKSEWW8080: missing port in address

 

Summary

As we can see, split functions typically return a string slice that includes every piece that was divided. We can use a string slice as the assigned return value. For some special split functions, the return values may different than the string slice. For example, the net.SplitHostPort() function which split an IP address return three values: the host, the port, and the error.

 

References

https://pkg.go.dev/net#SplitHostPort
https://pkg.go.dev/strings#Split
How to split a string and assign it to variables - Stack Overflow

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment