Is there any way in Go to search for vowels and replace it with numbers in a given string? the program should randomly replace the vowels with numbers and display the formatted string
package main
import (
"fmt"
"strings"
)
func main() {
vowels := map[rune]rune{
'a': '3',
'e': '2',
'i': '1',
}
var s string
s = strings.Map(func(r rune) rune {
if u, ok := vowels[r]; ok {
return u
}
return r
}, s)
fmt.Println(s)
}
but still it is not printing the random strings .. please suggest
I would suggest using strings.Map
for this:
s = strings.Map(func(r rune) rune {
switch r {
case 'a':
return '3'
case 'e':
return '2'
// etc.
default:
return r
}
}, s)
https://play.golang.org/p/D66J5hZsNs
With a slight modification, if you need to dynamically set the replacement values, you could store the vowels in a map. For example:
vowels := map[rune]rune{
'a': '3',
'e': '2',
}
s = strings.Map(func(r rune) rune {
if u, ok := vowels[r]; ok {
return u
}
return r
}, s)