Strings in Go - Advanced

Strings in Go - Advanced

In this guide, we'll explore how to work with strings and the strconv package in Go, covering useful functions that help manipulate and convert strings.

Common String Operations

Go provides several built-in functions in the strings package that allow you to efficiently manage strings. Let’s dive into some of these handy functions.


Checking Prefixes and Suffixes

You can check if a string starts or ends with a specific prefix or suffix using the following functions:

  • strings.HasPrefix(s, prefix string) bool
    Returns true if the string s starts with the specified prefix.

  • strings.HasSuffix(s, suffix string) bool
    Returns true if the string s ends with the specified suffix.

Example:

str := "This is an example string"
fmt.Println(strings.HasPrefix(str, "This")) // true
fmt.Println(strings.HasSuffix(str, "string")) // true

Checking for Substrings

To test whether a string contains a particular substring, use the Contains function:

  • strings.Contains(s, substr string) bool
    Returns true if substr is found within s.

Example:

str := "Hello, world!"
fmt.Println(strings.Contains(str, "world")) // true

Finding the Index of Substrings or Characters

You can identify the position of a substring or character using the following functions:

  • strings.Index(s, substr string) int
    Returns the index of the first occurrence of substr in s, or -1 if not found.

  • strings.LastIndex(s, substr string) int
    Returns the index of the last occurrence of substr in s, or -1 if not found.

For non-ASCII characters, you can use IndexRune to find the index of a specific Unicode character:

  • strings.IndexRune(s string, ch rune) int

Example:

str := "Go is fun. Go is powerful."
fmt.Println(strings.Index(str, "Go"))      // 0
fmt.Println(strings.LastIndex(str, "Go"))  // 11

Replacing Substrings

You can replace occurrences of a substring with a new one using Replace:

  • strings.Replace(s, old, new string, n int) string
    Replaces the first n occurrences of old with new in s. If n is -1, all occurrences are replaced.

Example:

str := "banana"
fmt.Println(strings.Replace(str, "na", "HA", -1)) // "baHAHA"

Counting Occurrences of a Substring

You can count the number of times a substring appears using Count:

  • strings.Count(s, substr string) int
    Returns the count of non-overlapping occurrences of substr in s.

Example:

str := "cheese"
fmt.Println(strings.Count(str, "e")) // 3

Repeating Strings

To create a new string by repeating another string, use Repeat:

  • strings.Repeat(s string, count int) string
    Returns a string that consists of count copies of s.

Example:

str := "Go!"
fmt.Println(strings.Repeat(str, 3)) // "Go!Go!Go!"

Changing the Case of Strings

You can convert strings to uppercase or lowercase:

  • strings.ToLower(s string) string
    Converts s to lowercase.

  • strings.ToUpper(s string) string
    Converts s to uppercase.

Example:

str := "GoLang"
fmt.Println(strings.ToLower(str)) // "golang"
fmt.Println(strings.ToUpper(str)) // "GOLANG"

Trimming Strings

To remove leading and trailing spaces or specific characters from a string, use these functions:

  • strings.TrimSpace(s string) string
    Removes all leading and trailing whitespaces from s.

  • strings.Trim(s, cutset string) string
    Removes all leading and trailing occurrences of the characters in cutset from s.

Example:

str := "   hello   "
fmt.Println(strings.TrimSpace(str)) // "hello"

Splitting and Joining Strings

To split a string into slices or join slices back into a string, use these functions:

  • strings.Fields(s string) []string
    Splits s into a slice based on whitespace.

  • strings.Split(s, sep string) []string
    Splits s around the separator sep.

  • strings.Join(sl []string, sep string) string
    Joins the elements of the slice sl into a string, separated by sep.

Example:

str := "a,b,c"
parts := strings.Split(str, ",")
fmt.Println(parts) // ["a", "b", "c"]

joined := strings.Join(parts, ";")
fmt.Println(joined) // "a;b;c"

Reading from a String

You can create a Reader from a string, which provides methods like Read and ReadRune for reading the content:

  • strings.NewReader(s string) *Reader

String Conversions with strconv

The strconv package provides several useful functions for converting between strings and other data types:

  • strconv.Itoa(i int) string
    Converts an integer i to its decimal string representation.

  • strconv.Atoi(s string) (int, error)
    Converts a string s into an integer. Returns an error if the string is not a valid number.

  • strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string
    Converts a floating-point number f to a string with specified format and precision.

Example:

numStr := "123"
num, err := strconv.Atoi(numStr)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(num) // 123
}

That's a wrap for working with strings and the strconv package in Go. Up next, we’ll explore the powerful time management capabilities of Go's time package.