How to replace all characters in a string in golang
By replacing all characters you would get a string
with the same character count, but all being '*'
. So simply construct a string
with the same character-length but all being '*'
. strings.Repeat()
can repeat a string
(by concatenating it):
ss := []string{"golang", "pi", "世界"}
for _, s := range ss {
fmt.Println(s, strings.Repeat("*", utf8.RuneCountInString(s)))
}
Output (try it on the Go Playground):
golang ******
pi **
世界 **
Note that len(s)
gives you the length of the UTF-8 encoding form as this is how Go stores strings in memory. You can get the number of characters using utf8.RuneCountInString()
.
For example the following line:
fmt.Println(len("世界"), utf8.RuneCountInString("世界")) // Prints 6 2
prints 6 2
as the string "世界"
requires 6 bytes to encode (in UTF-8), but it has only 2 characters.
A simple way of doing it without something like a regex:
https://play.golang.org/p/B3c9Ket9fp
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Repeat("*", utf8.RuneCountInString("golang")))
}
Something more along the lines of what you were probably initially thinking:
https://play.golang.org/p/nbNNFJApPp
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(".")
fmt.Println(re.ReplaceAllString("golang", "*"))
}