7
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 "******"?

3
  • Can you please give us more examples of what how you would like this to behave? Commented Apr 29, 2016 at 5:44
  • ex: if i am getting a string like "INHERITED" i want to convert it into "*********" Commented Apr 29, 2016 at 5:47
  • 1
    Do you mean strings.Replace("golang", "golang", "******", -1) ? Commented Apr 29, 2016 at 5:48

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good call on the multibyte characters.
14

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", "*"))
}

1 Comment

Seems the answer of icza should be set as accepted because it takes into account that string may have multibyte runes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.