How to Split a String by Space in Go Language

Example 1: Using Split() Method

The Split() method​ in Go defined in the strings library splits a string down into a list of substrings using a specified separator. The method returns the substrings in the form of a slice.
package main

import (
"fmt"
"strings"
)

func main() {

str := "Go C C++ Python Java Kotlin Php JS"

//split string using Split() method
out := strings.Split(str, " ")

for j := 0; j < len(out); j++ {
fmt.Println(out[j])
}
}

Output:



Example 2: Using Fields() Method

The Fields() method in the strings package separates these into an array. It splits into groups of spaces.
package main

import (
"fmt"
"strings"
)

func main() {

str := "Go C C++ Python Java Kotlin Php JS"

//split string using Fields() method
out := strings.Fields(str)

for j := 0; j < len(out); j++ {
fmt.Println(out[j])
}
}

Output:



Example 3: Using Regular expressions

Regular expressions can be used to split the string using the pattern of the delimiters
package main

import (
"fmt"
"regexp"
)

func main() {

str := "Go C C++ Python Java Kotlin Php JS"

//split string using regexp
regx := regexp.MustCompile(`[ ]`)
//arg -1 means no limits for the number of substrings
out := regx.Split(str, -1)

for j := 0; j < len(out); j++ {
fmt.Println(out[j])
}
}

Output:


Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Java - How to Count the Number of Occurrences of Substring in a String

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

Custom Exception Handling in Quarkus REST API

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024