英文:
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 -> 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 + "*"
}
}
</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 < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论