Home > Software design >  How to replace string in Golang?
How to replace string in Golang?

Time:12-07

I want to replace username except first and last alphabet.

For example:

handsome -> h******e

한국어    -> 한*어

This is my code:

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

CodePudding user response:

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.

  • Related