golang

Golang Strings

A string refers to a sequence of one or more characters, including letters, numbers, and special characters. Strings are a critical concept in most programming languages despite the simplistic definition.

This is because strings help us work with textual information within our programs. Typically, it is difficult to build a non-trivial application without using strings.

In this guide, we will cover the basics of working with strings in the go programming language.

What is a string?

In go, we refer to a string as a read-only slice of bytes. We can create a string in go by enclosing the sequence of characters inside double quotes or back quotes.

Keep in mind that the method you use to create a string in Go matters.

Using back ticks (“) to create a string in go creates a raw string literal. A raw string literal means that the string can contain any character except for a back tick.

The following example shows a raw string literal.

raw_string :=  `this is a string`

Unlike interpreted string literals created using double quotes, backlash characters have no special denotation inside a raw string literal. For example, \n, which can insert a newline character in interpreted strings, we print it as is in raw string literals.

To create an interpreted string literal in go, enclose the set of characters in double-quotes, as shown in the example below:

interpreted_string := "This is a string"

Here, backlash characters are interpreted to hold a special meaning. For example, to insert a new line in the string, we can use \n as:

interpreted_string := "This is \n a string"

It is common to use interpreted string literal as they allow you to add special characters and escape sequences.

Go, Print String

You can print a string in go using the Println() method from the fmt package. Ensure to import the package before calling the method. An example code is as shown:

package main

import "fmt"

func main()  {
    fmt.Println("This is a string")
}

The above code uses the fmt.Println() method to print an interpreted string literal. You can also store a string as a variable and reference it in the method as shown:

package main

import "fmt"

func main()  {
    my_string := "This is a string"
    fmt.Println(my_string)
}

String Operations in Go

There is a collection of operations you can perform on string types. Go provides a set of methods to perform string operations in the strings package.

https://pkg.go.dev/strings

Let us look at a few operations you can perform on strings.

String Concatenation

String concatenation refers to the technique of combining two or more string literals together to create a new string.

In go, we can concatenate strings using the addition (+) operator.

For example, let us combine the strings “linux” and “hint” as shown.

package main
import "fmt"
func main()  {
    fmt.Println("linux" + "hint")
}

If we run the code above, we should get an output as:

$ go run golang_strings.go
linuxhint

Keep in mind that you cannot use the addition operator (+) with values of different types. For example, if you try to concatenate a string and an int, you will get an error as:

fmt.Println("linux" + 12)

The code above returns an error as:

invalid operation: "linux" + 12 (mismatched types untyped string and untyped int)

A way to overcome this is to enclose both values into double-quotes. This converts the numerical value into a string, allowing you to perform string concatenation.

String concatenation always results in a new string which you can store in a variable and re-use in other parts of your program.

Convert String to Lowercase or Uppercase

As mentioned, Go provides us with the strings package, which allows you to perform operations on string types.

Two useful methods from the package are ToLower and ToUpper, which convert a string to lowercase and uppercase, respectively.

NOTE: In go, string types are immutable. This means that you cannot change the original value of the string once created.

The example below converts the string “LinuxHint” to lowercase.

package main
import "fmt"
import "strings"
func main() {
    my_string := "LinuxHint"
    fmt.Println(strings.ToLower(my_string))
}

The ToLower() function takes the string to convert to lowercase as the argument. It then returns the sequence of characters of the string converted to lowercase. The function returns a new string, as strings are immutable data types.

If we run the above code, we should get an output as:

linuxhint

To convert a string to uppercase, we can use the ToUpper() method, as shown in the example below:

my_string := "LinuxHint"
fmt.Println(strings.ToUpper(my_string))

The resulting string is as shown:

LINUXHINT

Get String Length

To get the length of a string in go, you can use the len() method and pass the string as the argument.

The method will return the number of characters in the string.

For example:

my_string := "LinuxHint"
fmt.Println(len(my_string))

Once we run the code above, we should get the number of characters of the string as:

$ go run golang_strings.go
9

The number of characters, in this case, refers to any character enclosed in double quotes, including symbols and other special characters.

Check if string contains

You can also search for a substring in go using the contains method. The method accepts the main string in which to search for the substring and the substring to search and as the arguments.

The function then returns a Boolean value if the substring is found and false otherwise.

Consider the example shown below:

package main
import (
    "fmt"
    "strings"
)
func main() {
    full_string := "Welcome to the go programming langugae!"
    fmt.Println(strings.Contains(full_string, "go"))
}

Once we run the code above, we should get an output as:

$ go run golang_strings.go
true

The substring “go” is found in the full_string variable; the function returns true.

Conclusion

This tutorial covers the basics of working with strings in Go. If you are getting started in go, check our tutorials on the topic to learn more. You can also check the documentation for added information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list