Go String Manipulation and Type Conversion Basics

Lesson Overview

Welcome! In this lesson, we'll delve into the basic string manipulation features of Go, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations.

Tokenizing a String in Go

In Go, you can split a string into smaller parts, or tokens, using the strings.Split function from the strings package. Here's an example:

package main

import (
    "fmt"
    "strings"
)

func main() {
    sentence := "Go is an amazing language!"
    tokens := strings.Split(sentence, " ")

    for _, token := range tokens {
        fmt.Println(token)
    }
    // Output:
    // Go
    // is
    // an
    // amazing
    // language!
}

In the example above, we use a space as a delimiter to split the sentence into individual words with strings.Split(sentence, " "). Then, the for loop prints each word in the sentence on a new line.

Exploring String Concatenation

In Go, strings can be concatenated using the + operator:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str1 := "Hello,"
    str2 := " World!"
    greeting := str1 + str2
    fmt.Println(greeting) // Output: "Hello, World!"

    str3 := " Go is fun."
    greeting += str3
    fmt.Println(greeting) // Output: "Hello, World! Go is fun."
    
    words := []string{"Go", "is", "an", "amazing", "language"}
    sentence := strings.Join(words, " ")
    fmt.Println(sentence) // Output: "Go is an amazing language"
}

In this example, we use the + operator to construct a larger string from smaller strings. The += operator appends a string to the existing string, effectively creating a new string with the original content and the appended string. Recall that in Go strings are immutable, so both + and += result in the creation of a new string rather than modifying the original(s).

Additionally, we use the strings.Join function to concatenate elements from a slice of strings (words) into a single string (sentence). Here, a space is used as a separator between each word. This approach is efficient when concatenating multiple strings as it avoids creating multiple intermediate strings.

Trimming Whitespaces from Strings

In Go, you can use the strings.TrimSpace function to remove leading and trailing white spaces from a string:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "    Hello, World!    " // string with leading and trailing spaces
    str = strings.TrimSpace(str)
    fmt.Println(str) // Output: "Hello, World!"
}

In this example, strings.TrimSpace is used to remove all leading and trailing whitespaces from a string.

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