Q:

Golang program to replace all specified substrings by given substring

belongs to collection: Golang String Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 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 str1str2. 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

total answers (1)

Golang String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to convert the specified string int... >>
<< Golang program to get the index of last occurrence...