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
+7.1k Golang : Check if integer is power of four example
+9.4k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+22.7k Golang : Find biggest/largest number in array
+10.4k Golang : Convert decimal number(integer) to IPv4 address
+6.2k Golang : Dealing with struct's private part
+8.2k Golang : Terminate-stay-resident or daemonize your program?
+8.8k Golang : Get current, epoch time and display by year, month and day
+5.2k Apt-get to install and uninstall Golang
+17.8k Golang : How to get own program name during runtime ?
+27.8k Golang : JQuery AJAX post data to server and send data back to client example
+13.9k Golang : rune literal not terminated error
+18.1k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader