Table of contents
- Common String Operations
- Checking Prefixes and Suffixes
- Checking for Substrings
- Finding the Index of Substrings or Characters
- Replacing Substrings
- Counting Occurrences of a Substring
- Repeating Strings
- Changing the Case of Strings
- Trimming Strings
- Splitting and Joining Strings
- Reading from a String
- String Conversions with strconv
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
Returnstrue
if the strings
starts with the specifiedprefix
.strings.HasSuffix(s, suffix string) bool
Returnstrue
if the strings
ends 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
Returnstrue
ifsubstr
is 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 ofsubstr
ins
, or-1
if not found.strings.LastIndex(s, substr string) int
Returns the index of the last occurrence ofsubstr
ins
, 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 firstn
occurrences ofold
withnew
ins
. Ifn
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 ofsubstr
ins
.
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 ofcount
copies 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
Convertss
to lowercase.strings.ToUpper(s string) string
Convertss
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 froms
.strings.Trim(s, cutset string) string
Removes all leading and trailing occurrences of the characters incutset
froms
.
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
Splitss
into a slice based on whitespace.strings.Split(s, sep string) []string
Splitss
around the separatorsep
.strings.Join(sl []string, sep string) string
Joins the elements of the slicesl
into 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 integeri
to its decimal string representation.strconv.Atoi(s string) (int, error)
Converts a strings
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 numberf
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.