How to replace string in Golang?

huangapple go评论84阅读模式
英文:

How to replace string in Golang?

问题

我想要替换字符串,除了第一个和最后一个字母之外。

例如:

handsome -> h******e

한국어    -> 한*어

这是我的代码:

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

I want to replace string except first and last alphabet.

For example:

handsome -&gt; h******e

한국어    -&gt; 한*어

This is my code:

var final = string([]rune(username)[:1]
for i :=0l i &lt;len([]rune(username)); i++{
 if i &gt;1 {
  final = final + &quot;*&quot;
 }
}

</details>


# 答案1
**得分**: 3

如果将字符串转换为`[]rune`,你可以修改该切片,最后再将其转换回`string`:

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

测试一下:

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

输出结果(在Go Playground上尝试):

h******e
한*어

请注意,这个blur()函数也适用于长度小于3的字符串,此时不会有任何字符被模糊化。

英文:

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 &lt; len(rs)-1; i++ {
		rs[i] = &#39;*&#39;
	}
	return string(rs)
}

Testing it:

fmt.Println(blur(&quot;handsome&quot;))
fmt.Println(blur(&quot;한국어&quot;))

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.

huangapple
  • 本文由 发表于 2021年12月7日 18:00:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/70258112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定