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
+32.2k Golang : Validate email address with regular expression
+10.1k Golang : Test a slice of integers for odd and even numbers
+10.6k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+7.4k Golang : How to detect if a sentence ends with a punctuation?
+6k Golang : Extract unicode string from another unicode string example
+25.3k Golang : Storing cookies in http.CookieJar example
+6.3k Golang : Calculate US Dollar Index (DXY)
+24.6k Golang : GORM read from database example
+9.5k Facebook : Getting the friends list with PHP return JSON format
+19.6k Golang : Set or Add HTTP Request Headers
+12.6k Golang : Arithmetic operation with numerical slices or arrays example
+10.6k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine