Sobes.tech
Junior

How can you work with strings in Go?

sobes.tech AI

Answer from AI

In Go, strings are immutable sequences of bytes.

Main ways to work with strings:

  1. Creation:

    // String literal
    s1 := "Hello, Go!"
    
    // From a byte slice
    byteArray := []byte{'H', 'e', 'l', 'l', 'o'}
    s2 := string(byteArray)
    
  2. Concatenation:

    s3 := "World"
    result := s1 + " " + s3 // Using the + operator
    

    For many concatenations, it is more efficient to use strings.Builder:

    import "strings"
    
    var sb strings.Builder
    sb.WriteString("Hello")
    sb.WriteString(", ")
    sb.WriteString("World!")
    result2 := sb.String()
    
  3. Length:

    • In bytes:
      byteLength := len(s1)
      
    • In characters (runes):
      runeLength := utf8.RuneCountInString(s1) // Requires import "unicode/utf8"
      
  4. Accessing characters (runes) and iteration: In Go, strings consist of bytes, but when iterated with range, they are decoded into runes (Unicode code points).

    import "fmt"
    
    for index, runeValue := range s1 {
        fmt.Printf("Index: %d, Rune: %c, Type: %T\n", index, runeValue, runeValue)
    }
    

    Direct index access returns a byte, not a rune:

    b := s1[0] // Returns byte 'H'
    
  5. Conversion:

    • To a byte slice:
      byteSlice := []byte(s1)
      
    • To a rune slice:
      runeSlice := []rune(s1)
      
  6. strings package: Provides many useful functions for string manipulation:

    • strings.Contains(s, substr): Checks if a substring exists.
    • strings.HasPrefix(s, prefix): Checks for a prefix.
    • strings.HasSuffix(s, suffix): Checks for a suffix.
    • strings.Index(s, substr): Finds the first occurrence of a substring.
    • strings.ReplaceAll(s, old, new): Replaces all occurrences of a substring.
    • strings.Split(s, sep): Splits a string by a separator.
    • strings.Join(a []string, sep string): Joins a slice of strings.
    • strings.ToLower(s): Converts to lowercase.
    • strings.ToUpper(s): Converts to uppercase.
    • strings.TrimSpace(s): Removes whitespace from the beginning and end.
  7. fmt package: For formatted output and scanning strings.

  8. strconv package: For converting strings to numeric types and vice versa.

    import "strconv"
    
    i, err := strconv.Atoi("123") // String to int
    s := strconv.Itoa(i)         // Int to string
    

Immutability of strings is important and means that any operation that seems to modify a string (e.g., concatenation or Replace) actually creates a new string.