How to replace specific word in a string in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to replace specific word in a string using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import (
"fmt"
"strings"
)
func main() {
// Define the input string
str := "The quick brown fox jumps over the lazy dog"
// Define the words to replace and their replacements
wordsToReplace := map[string]string{
"quick": "slow",
"lazy": "energetic",
}
// Loop through the words to replace
for word, replacement := range wordsToReplace {
// Replace the word with the replacement string
str = strings.ReplaceAll(str, word, replacement)
}
// Print the modified string to the console
fmt.Println("String with replaced words:", str)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we define the input string str as "The quick brown fox jumps over the lazy dog", and the words to replace as a map with keys and values representing the words to replace and their replacements, respectively.
We then use a for loop to loop through the words to replace, and for each word we use the strings.ReplaceAll function to replace all occurrences of the word with its replacement.
#go #goprogramming #golang #golangtutorial #golanguage