package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("golang", "g", "1", -1))
}
How to replace all characters in string "golang"
(above string) by *
that is it should look like "******"
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With