Go Gopher How to Go

Strings in Go are immutable sequences of bytes, typically used to represent UTF-8 encoded text. Go provides rich support for string manipulation through the strings package and built-in operations.

💡 Key Points

  • Strings are immutable - once created, they cannot be changed
  • Strings are represented as UTF-8 encoded byte sequences
  • Use double quotes for string literals: "hello"
  • Use backticks for raw string literals: `hello\nworld`
  • String concatenation creates new strings
  • Indexing a string returns bytes, not characters
  • The strings package provides extensive string manipulation functions
  • Use len() to get byte length, not character count

String Basics

Strings can be created using double quotes or backticks for raw strings:

package main

import "fmt"

func main() {
    // Regular string with double quotes
    s1 := "Hello, World!"
    fmt.Println(s1)
    
    // Raw string with backticks (ignores escape sequences)
    s2 := `Line 1
Line 2
Line 3`
    fmt.Println(s2)
    
    // String concatenation
    greeting := "Hello" + " " + "World"
    fmt.Println(greeting)
    
    // String length (in bytes)
    fmt.Println("Length:", len(s1))
    
    // Accessing bytes
    fmt.Println("First byte:", s1[0])
}
Output:
Hello, World!
Line 1
Line 2
Line 3
Hello World
Length: 13
First byte: 72

String Operations

The strings package provides many useful functions for working with strings:

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Hello, Go Programming"
    
    // Check if string contains substring
    fmt.Println("Contains 'Go':", strings.Contains(s, "Go"))
    
    // Count occurrences
    fmt.Println("Count 'o':", strings.Count(s, "o"))
    
    // Check prefix/suffix
    fmt.Println("Starts with 'Hello':", strings.HasPrefix(s, "Hello"))
    fmt.Println("Ends with 'ing':", strings.HasSuffix(s, "ing"))
    
    // Find index
    fmt.Println("Index of 'Go':", strings.Index(s, "Go"))
    
    // Join strings
    parts := []string{"Go", "is", "awesome"}
    joined := strings.Join(parts, " ")
    fmt.Println("Joined:", joined)
    
    // Split strings
    split := strings.Split(s, " ")
    fmt.Println("Split:", split)
    
    // Replace
    replaced := strings.Replace(s, "Go", "Golang", 1)
    fmt.Println("Replaced:", replaced)
    
    // Case conversion
    fmt.Println("Upper:", strings.ToUpper(s))
    fmt.Println("Lower:", strings.ToLower(s))
    
    // Trim whitespace
    padded := "  spaces  "
    fmt.Println("Trimmed:", strings.TrimSpace(padded))
}
Output:
Contains 'Go': true
Count 'o': 3
Starts with 'Hello': true
Ends with 'ing': true
Index of 'Go': 7
Joined: Go is awesome
Split: [Hello, Go Programming]
Replaced: Hello, Golang Programming
Upper: HELLO, GO PROGRAMMING
Lower: hello, go programming
Trimmed: spaces

Common String Functions

FunctionDescriptionExample
strings.Contains(s, substr)Check if string contains substringstrings.Contains("hello", "lo")
strings.Count(s, substr)Count non-overlapping instancesstrings.Count("cheese", "e")
strings.HasPrefix(s, prefix)Check if string starts with prefixstrings.HasPrefix("go", "g")
strings.HasSuffix(s, suffix)Check if string ends with suffixstrings.HasSuffix("go", "o")
strings.Index(s, substr)Find index of first occurrencestrings.Index("hello", "l")
strings.Join(slice, sep)Join slice elements with separatorstrings.Join([]string{"a","b"}, "-")
strings.Split(s, sep)Split string by separatorstrings.Split("a-b-c", "-")
strings.Replace(s, old, new, n)Replace first n occurrencesstrings.Replace(s, "a", "b", 1)
strings.ToLower(s)Convert to lowercasestrings.ToLower("HELLO")
strings.ToUpper(s)Convert to uppercasestrings.ToUpper("hello")
strings.TrimSpace(s)Remove leading/trailing whitespacestrings.TrimSpace(" hi ")

String Building

MethodPerformanceUse Case
+ operatorSlow for many concatenationsConcatenating few strings
strings.BuilderFast, minimal allocationsBuilding strings in loops
fmt.SprintfModerateFormatted string construction
strings.JoinFast for slicesJoining slice of strings

String Characteristics

FeatureDescriptionNotes
ImmutabilityStrings cannot be modifiedModifications create new strings
UTF-8 EncodingStrings are UTF-8 by defaultSupports international characters
Byte SequencesStrings are byte arraysIndexing returns bytes, not runes
Lengthlen() returns byte countNot the same as character count
ComparisonCompared lexicographicallyUse ==, <, >
Zero ValueEmpty string ""Not nil