Lesson Introduction

Welcome! Today, we're going to delve into the crucial operations associated with Strings in Go. Strings are fundamental in most programming languages as they are used for displaying and manipulating textual data. In this lesson, you'll learn about the basic string operations in Go, such as concatenation, comparison, and the use of common functions from the strings package.

Revising String Concatenation

Even though we already know what concatenation is and how it works, revisiting it strengthens our understanding! Concatenation — the process of joining items together — is a principal string operation. In Go, we achieve string concatenation by using the + operator.

package main

import "fmt"

func main() {
    var hello = "Hello, "
    var world = "World!"
    var greeting = hello + world

    fmt.Println(greeting) // "Hello, World!"
}

In this case, "Hello, " and "World!" were combined to form the string "Hello, World!".

Comparing Strings

There are often times when we need to compare strings. Fortunately, in Go, the simple comparison operators == and < work perfectly fine.

package main

import "fmt"

func main() {
    var firstWord = "Hello"
    var secondWord = "Hello"
    var areEqual = firstWord == secondWord

    fmt.Println(areEqual) // Outputs: true
}

Here, as firstWord and secondWord are equal, areEqual is true.

The < operator is used to determine if one string is alphabetically before the other.

package main

import "fmt"

func main() {
    var firstWord = "Apple"
    var secondWord = "Banana"
    var isLess = firstWord < secondWord
    
    fmt.Println(firstWord, "is less than", secondWord, "?", isLess) // Outputs: Apple is less than Banana? true
}

As you can see, the comparison result is true, which means that alphabetically, "Apple" comes before "Banana", because A comes before B. A string that would come before another string in the dictionary is considered less than the other. In case of a tie, Go will compare the following letter. For example, "Apple" will be less than "Application", because e is less than i. As the first four letters in the words are equal, Go compares the fifth one.

Important String Functions: len
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