How to replace string in Golang?

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

How to replace string in Golang?

问题

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

例如:

  1. handsome -> h******e
  2. 한국어 -> 한*어

这是我的代码:

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

I want to replace string except first and last alphabet.

For example:

  1. handsome -&gt; h******e
  2. 한국어 -&gt; 한*어

This is my code:

  1. var final = string([]rune(username)[:1]
  2. for i :=0l i &lt;len([]rune(username)); i++{
  3. if i &gt;1 {
  4. final = final + &quot;*&quot;
  5. }
  6. }
  7. </details>
  8. # 答案1
  9. **得分**: 3
  10. 如果将字符串转换为`[]rune`,你可以修改该切片,最后再将其转换回`string`
  11. ```go
  12. func blur(s string) string {
  13. rs := []rune(s)
  14. for i := 1; i < len(rs)-1; i++ {
  15. rs[i] = '*'
  16. }
  17. return string(rs)
  18. }

测试一下:

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

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

  1. h******e
  2. 한*어

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

英文:

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

  1. func blur(s string) string {
  2. rs := []rune(s)
  3. for i := 1; i &lt; len(rs)-1; i++ {
  4. rs[i] = &#39;*&#39;
  5. }
  6. return string(rs)
  7. }

Testing it:

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

Output (try it on the Go Playground):

  1. h******e
  2. 한*어

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:

确定