212 words
1 minutes
String Manipulation in Golang
In Go, we have the strings
package for string manipulation. Some common string manipulation operations:
String Replacement
The strings.Replace
function is used to replace occurrences of a substring within a string. It takes four arguments: the original string, the substring to be replaced, the replacement substring, and the maximum number of replacements to make.
package main
import (
"fmt"
"strings"
)
func stringsII() {
// Define first and last names
firstName := "Rabi"
lastName := "Siddique"
// Replace 'i' with 'ee' in firstName (up to 2 occurrences)
a := strings.Replace(firstName, "i", "ee", 2)
// Replace 'Si' with 'Sa' in lastName (up to 1 occurrence)
b := strings.Replace(lastName, "Si", "Sa", 1)
// Print the original and modified strings
fmt.Println(firstName + " " + lastName) // Output: Rabi Siddique
fmt.Println(a + " " + b) // Output: Rabee Saddique
}
func main() {
stringsII()
}
String Builder
For efficient string concatenation, Go provides the strings.Builder
type. This type is optimized for building strings by minimizing memory reallocations.
package main
import (
"fmt"
"strings"
)
func stringsII() {
// Create a new strings.Builder
var builder strings.Builder
// Write strings to the builder
builder.WriteString("Hello")
builder.WriteString(" ")
builder.WriteString("World")
// Convert the builder contents to a string and print it
fmt.Println(builder.String()) // Output: Hello World
}
func main() {
stringsII()
}
String Manipulation in Golang
https://rabisiddique.com/posts/strings-in-golang/Author
Rabi Siddique
Published at
2023-03-17