Strings in Go



In this tutorial, we will learn about strings in Go. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in Go is a sequence of bytes. Strings in Go are immutable, meaning their values cannot be changed once created. Strings are used for storing and handling text data.


Creating Strings

Strings can be created in Go using double quotes:

var str string = "Hello, world!"

Strings can also be created using backticks for raw string literals:

var str2 string = `Hello, world!`


Example 1: Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using fmt.Println.

Go Program

package main
import "fmt"
func main() {
    var str string = "Hello, world!"
    fmt.Println(str)
}

Output

Hello, world!


Example 2: Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using array indexing.

Go Program

package main
import "fmt"
func main() {
    var str string = "Hello"
    fmt.Println(string(str[0])) // Accessing using array indexing
    fmt.Println(string(str[1]))
}

Output

H
e


Example 3: Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in Go are immutable, so create a new string with the modified value.
  3. Print the modified string.

Go Program

package main
import "fmt"
func main() {
    var str string = "Hello"
    str = "J" + str[1:]
    str += " World!"
    fmt.Println(str)
}

Output

Jello World!


Example 4: String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the + operator.
  3. Print the concatenated string.

Go Program

package main
import "fmt"
func main() {
    var str1 string = "Hello"
    var str2 string = " World!"
    var str3 string = str1 + str2
    fmt.Println(str3)
}

Output

Hello World!


Example 5: Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the strings.Index function to find a substring.
  3. Print the position of the found substring.

Go Program

package main
import (
    "fmt"
    "strings"
)
func main() {
    var str string = "Hello, world!"
    pos := strings.Index(str, "world")
    if pos != -1 {
        fmt.Printf("Found 'world' at position: %d\n", pos)
    } else {
        fmt.Println("Substring not found")
    }
}

Output

Found 'world' at position: 7


Example 6: String Length

  1. Create a string variable and initialize it with a value.
  2. Use the len function to get the length of the string.
  3. Print the length of the string.

Go Program

package main
import "fmt"
func main() {
    var str string = "Hello, world!"
    fmt.Printf("Length of the string: %d\n", len(str))
}

Output

Length of the string: 13