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
Returnstrueif the stringsstarts with the specifiedprefix.strings.HasSuffix(s, suffix string) bool
Returnstrueif the stringsends with the specifiedsuffix.
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
Returnstrueifsubstris found withins.
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 ofsubstrins, or-1if not found.strings.LastIndex(s, substr string) int
Returns the index of the last occurrence ofsubstrins, or-1if 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 firstnoccurrences ofoldwithnewins. Ifnis-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 ofsubstrins.
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 ofcountcopies ofs.
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
Convertssto lowercase.strings.ToUpper(s string) string
Convertssto 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 froms.strings.Trim(s, cutset string) string
Removes all leading and trailing occurrences of the characters incutsetfroms.
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
Splitssinto a slice based on whitespace.strings.Split(s, sep string) []string
Splitssaround the separatorsep.strings.Join(sl []string, sep string) string
Joins the elements of the sliceslinto a string, separated bysep.
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 integerito its decimal string representation.strconv.Atoi(s string) (int, error)
Converts a stringsinto 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 numberfto 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.



