Reputation: 127
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.
Upvotes: 3
Views: 2406
Reputation: 417867
strings.ReplaceAll()
does not perform "switching", it just replaces the occurrences of some string with another; but it doesn't execute replacing another with some. Meaning ReplaceAll(s, "a", "b")
will replace all occurrences of "a"
with "b"
, but it will not replace occurrences of "b"
with "a"
.
That's 2 replace operations. And these 2 replace operations can't be executed sequentially, because once you replace "apple"s with "mango"s, you'll only have "mango"s and so if you'd replace "mango"s with "apple"s, you'd be left with "apple"s only.
Instead you may use strings.Replacer
where you may list multiple replaceable pairs, and its Replacer.Replace()
method will perform all replaces in one step.
Also note that you should not replace all "a"s with "an" as there could be other "a"s in your input, not just before "mango". So best is if you replace "an apple" with "a mango" and vice versa.
s := "I have an apple but not a mango, and she has a mango but not an apple"
fmt.Println(s)
r := strings.NewReplacer("an apple", "a mango", "a mango", "an apple")
s = r.Replace(s)
fmt.Println(s)
Output (try it on the Go Playground):
I have an apple but not a mango, and she has a mango but not an apple
I have a mango but not an apple, and she has an apple but not a mango
Upvotes: 5