What is string in Go language?

Overview

String is a data type in Go language and represents a slice of bytes that are UTF-8 encodedUTF-8 transforms a code point (single character in Unicode) into a set of one to four bytes. This means that strings in Go language can represent a vast variety of characters. Strings are enclosed within double-quotes "". These strings are read-only and their values cannot be changed once defined.

Example

Below is a simple example of how strings are defined and printed in Go:

package main
import "fmt"
func main() {
str := "Hello World" //define string
fmt.Println(str) // print string
}

Escape sequences

The following table contains a list of escape sequences when a string is enclosed in double-quotes:

Escape sequence

Purpose

\'

Single quote

\"

Double quote

\n

New line

\t

Horizontal tab

\v

Vertical tab

\001

A 3-digit code that represents an 8-bit unicode character

\b

Backspace

\a

An alert or bell sound

\r

Return to start of the line (carriage feed)

\f

Go to the next page (form feed)

\xhh

Byte where h= hexadecimal digit

\uhhhh or \Uhhhhhhhh

Unicode character of either 4 or 8 hexadecimal digits respectively

What is length of string?

The length of a string can be found by using the len() function in Go language. Below is an example that highlights how one can check the length of a string:

package main
import "fmt"
/* For exercises uncomment the imports below */
// import "strconv"
// import "encoding/json"
func main() {
str := "Hello world!"
length := len(str)
fmt.Println("The length of the string is", length)
}

How to iterate over a string

You can iterate over a string by using a loop that accesses each character as well as the index of a string. Below is an example that demonstrates how you can loop over a string:

package main
import "fmt"
/* For exercises uncomment the imports below */
// import "strconv"
// import "encoding/json"
func main() {
str := "Hello world!"
for index,character := range str {
fmt.Printf("Character: %c Index %d\n", character, index)
}
}
Copyright ©2024 Educative, Inc. All rights reserved