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.
The source code to replace all specified substrings by given substring is given below. The given program is compiled and executed successfully.
// 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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer