In Go, you can replace a substring using strings.ReplaceAll(), which replaces every occurrence of the old substring with the new one:
result := strings.ReplaceAll(sentence, "cats", "dogs")
// "cats" is the substring to find
// "dogs" is the replacement
Here is an example:
sentence := "I love cats"
result := strings.ReplaceAll(sentence, "cats", "dogs")
fmt.Println(result) // "I love dogs"
Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!
Hint
Use strings.ReplaceAll(sentence, "cats", "dogs") and assign the result to result.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
