Reputation: 313
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 "******"
?
Upvotes: 7
Views: 19295
Reputation: 5232
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", "*"))
}
Upvotes: 14
Reputation: 417682
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.
Upvotes: 16