Home »
Golang »
Golang Programs
Golang program to replace all specified substrings by given substring
Here, we are going to learn how to replace all specified substrings by given substring in Golang (Go Language)?
Submitted by Nidhi, on March 20, 2021 [Last updated : March 03, 2023]
Replacing all specified substrings by given substring in Golang
Problem Solution:
In this program, we will create two strings, and replace all specified substrings by the specified substring using strings.ReplaceAll() function and then print update string on the console screen.
Program/Source Code:
The source code to replace all specified substrings by given substring is given below. The given program is compiled and executed successfully.
Golang code to replace all specified substrings by given substring
// Golang program to replace all specified
// substrings by given substring
package main
import "fmt"
import "strings"
func main() {
str1 := "ABC PQR LMN PQR"
str2 := "XYZ LMN LMN PQR"
fmt.Println(strings.ReplaceAll(str1, "PQR", "TUV"))
fmt.Println(strings.ReplaceAll(str2, "XYZ", "ABC"))
}
Output:
ABC TUV LMN TUV
ABC LMN LMN PQR
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we created two string variables str1, str2. Then we used strings.ReplaceAll() function to replace specified substring at all place in the string by another substring. After that, we printed the updated string on the console screen.
Golang String Programs »