Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
string

Strings in Golang

Educative Answers Team

Package strings implement simple functions to manipulate UTF-8 encoded strings.

Unlike JavaScript, strings are defined between double quotes “…”, not single quotes. Strings in Go are UTF-8 encoded by default. Due to UTF-8 encoding, Golang strings can contain a text which has​ characters from any language in the world.

Declaring a string

To define an empty variable of string type, use the string keyword. The following code demonstrates how to initialize a string.

package main
import "fmt"

func main() {
  var s string = "Hello, World"
  fmt.Printf(s)
}

Finding the length of a string

The len function is used to find the length of a string. The len function is made available in Go runtime; therefore, ​no packages need to be imported for this.

package main
import "fmt"

func main() {
  var s string = "Hello, World"
  fmt.Printf("%d",len(s))
}

Changing characters in a string

Golang strings are immutable, which means that they cannot be changed once they have been initialized. Changing these strings after initialization will cause the program to throw an ​error.

package main
import "fmt"

func main() {
  var s string = "Hello, World"
  
  // Uncomment the following line to change a value
  // in the string. A error will be thrown.
  // s[1] = 'c'

  fmt.Printf("%s",s)
}

Looping over characters in a string

We can access individual elements in a Golang string using a for loop (shown in the example below).

package main
import "fmt"

func main() {
  var s string = "Hello, World"
  
  for index, character := range(s){
    fmt.Printf("The character %c is in position %d \n", character, index)
  }
}

Create a string from a slice

We can also form a string from a slice of byte values using Golang strings.

package main
import "fmt"

func main() {
  myslice := []byte{0x48, 0x65, 0x6C,  0x6C, 0x6f} 
  mystring := string(myslice) 

  fmt.Printf(mystring)
}

Further functions related to string operations can be found in the official documentation page.

RELATED TAGS

golang
go
string
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring