Find and replace a character in a string in Go
String manipulation functions are a must have for a programming language and Go has plenty of them. In this tutorial we will see how to find and replace characters in a string.
strings.Replace() function will take in 4 parameters.
- First is the input string.
- Second is characters or words to find
- Third is the new replacement
- Fourth is the number ( n ) of instances found and to be replaced.
If n < 0, there is no limit on the number of replacements.
To find and replace white spaces from a string
str := " This string has many spaces that need to be replaced "
fmt.Println(strings.Replace(str, " ", "", -1))
because we want to remove unlimited instances of spaces in the string. We will use -1 as the fourth parameter. You can use -20 or -5 if you want. Remember the rule :
If n < 0, there is no limit on the number of replacements.
The above code output will be :
Thisstringhasmanyspacesthatneedtobereplaced
Full example code :
package main
import (
"fmt"
"strings"
)
func main() {
str := " This string has many many spaces that need to be replaced "
fmt.Println(strings.Replace(str, " ", "", -1))
str2 := " This string has much much spaces that need to be replaced "
fmt.Println(strings.Replace(str2, "much", "many", 2))
}
output :
Thisstringhasmanymanyspacesthatneedtobereplaced
This string has many many spaces that need to be replaced
Reference :
See also : Golang :Trim white spaces from a string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9k Golang : How to check if a string with spaces in between is numeric?
+10.2k Golang : Generate random integer or float number
+14.9k Golang : Get HTTP protocol version example
+9k Golang : How to control fmt or log print format?
+8.7k Golang : Get SPF and DMARC from email headers to fight spam
+5.9k Golang : Extract XML attribute data with attr field tag example
+11.5k Golang : Verify Linux user password again before executing a program example
+16.3k Golang : File path independent of Operating System
+7.1k Android Studio : How to detect camera, activate and capture example
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+25.1k Golang : Daemonizing a simple web server process example
+17.4k Golang : Read data from config file and assign to variables