Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace string in Golang?

I want to replace username except first and last alphabet.

For example:

handsome -> h******e

한국어    -> 한*어

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var final = string([]rune(username)[:1]
for i :=0l i <len([]rune(username)); i++{
 if i >1 {
  final = final + "*"
 }
}

>Solution :

If you convert the string to []rune, you can modify that slice and convert it back to string in the end:

func blur(s string) string {
    rs := []rune(s)
    for i := 1; i < len(rs)-1; i++ {
        rs[i] = '*'
    }
    return string(rs)
}

Testing it:

fmt.Println(blur("handsome"))
fmt.Println(blur("한국어"))

Output (try it on the Go Playground):

h******e
한*어

Note that this blur() function works with strings that have less than 3 characters too, in which case nothing will be blurred.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading