I am trying to learn Go-lang and for this reason playing around with strings in Go. But I am unable to perform correct swapping of sub-strings in a string.
My code is:
package main
import (
"fmt"
"strings"
)
func main() {
mystr := "I have an apple but not a mango, and she has a mango but not an apple"
fmt.Println(mystr)
mystr = strings.ReplaceAll(mystr, "apple", "(apple)")
mystr = strings.ReplaceAll(mystr, "mango", "apple")
mystr = strings.ReplaceAll(mystr, "(apple)", "mango")
fmt.Println(mystr)
mystr = strings.ReplaceAll(mystr, "an", "(a)")
mystr = strings.ReplaceAll(mystr, "a", "an")
mystr = strings.ReplaceAll(mystr, "(an)", "a")
fmt.Println(mystr)
}
Output:
I have an apple but not a mango, and she has a mango but not an apple
I have an mango but not a apple, and she has a apple but not an mango
I hanve a mago but not an anpple, ad she hans an anpple but not a mago
Is there a way to input a list or dictionary (like in python) so I can define the swaps and don't need to use strings.ReplaceAll() multiple times.
For example:
apple -> mango
mango -> apple
a -> an
an -> a
Desired Output:
I have a mango but not an apple, and she has an apple but not a mango
I will be glad to learn about pros and cons of each, if there are multiple ways to do this.