Overview and Actualization

Hello, Adventurer! Today, we will learn about splitting and joining strings — two vital operations for processing textual data in Go. Are you ready? Let's start this journey!

Understanding String Splitting in Go

In this lesson, we will use the following imports:

package main

import (
    "fmt"
    "strings"
)

In Go, the strings.Split function cuts a string into several pieces based on a delimiter, which is a character that separates words. It returns a slice containing these divided parts. Look at this example:

sentence := "I love programming."

// Let's split it into individual words
words := strings.Split(sentence, " ") // Now words = ["I", "love", "programming."]

// Loop through each word and print
for _, word := range words {
    fmt.Println(word)
}
// Prints:
// I
// Love
// Programming

Here, we have a sentence cut into separate words using the strings.Split() function, with a space as the delimiter. The results are stored in the slice words.

Mastering String Joining

The strings.Join() function merges a slice of strings back into a single string using a given delimiter. You can think of it as the inverse of the strings.Split() operation. Here's how it works:

// Our original words
words := []string{"programming.", "I", "love"}

// Let's join the words into a new sentence
sentence := strings.Join(words, " ")

fmt.Println(sentence)  // Output: "programming. I love"

In the example given above, we took a slice of words and combined them into a single string, using a space as the delimiter.

Combining Splitting and Joining

Both strings.Split() and strings.Join() can be used together to manipulate texts such as rearranging sentences. Let's take "I love programming" and rearrange it to "programming love I":

sentence := "I love programming."

// Split the sentence into words
words := strings.Split(sentence, " ")

// Swap the first and third words
tempWord := words[0]
words[0] = words[2]
words[2] = tempWord

// Join the words back into a sentence
newSentence := strings.Join(words, " ")

fmt.Println(newSentence) // Output: "programming. love I"

Here, we first split the sentence into words. Then, we swapped the positions of the first and last words before finally joining them back into a new sentence.

Moreover, strings.Join is flexible — it allows you to specify all parts to join one by one:

fmt.Println(strings.Join([]string{"See", "how", "you", "can", "join", "any", "number", "of", "words!"}, " "))
// Output: See how you can join any number of words!

It proves to be quite handy at times!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal