英文:
Ruby squeeze alternative in go
问题
Ruby的字符串有一个名为squeeze
的方法。根据Ruby文档的描述:
使用String#count中描述的过程,从other_str参数构建一个字符集。返回一个新的字符串,其中出现在该字符集中的相同字符的连续出现被替换为一个字符。如果没有给定参数,则所有相同字符的连续出现都被替换为一个字符。
在Golang中是否有类似的替代函数?如果没有,最佳的方法是什么?
英文:
Ruby strings had a method called squeeze
. From ruby docs :
> Builds a set of characters from the other_str parameter(s) using the
> procedure described for String#count. Returns a new string where runs
> of the same character that occur in this set are replaced by a single
> character. If no arguments are given, all runs of identical characters
> are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon"
" now is the".squeeze(" ") #=> " now is the"
"putters shoot balls".squeeze("m-z") #=> "puters shot balls"
IS there an alternative function for this operation in golang? If not whats the best way to do it in go?
答案1
得分: 4
你可以这样做:
func Squeeze(s string) string {
result := make([]rune, 0)
var previous rune
for _, r := range s {
if r != previous {
result = append(result, r)
}
previous = r
}
return string(result)
}
请注意,在Go语言中,字符串是UTF8编码的,因此为了与非ASCII字符串兼容,你必须使用符文(字符)而不是字节。
英文:
You can do it like this:
func Squeeze(s string) string {
result := make([]rune, 0)
var previous rune
for _, rune := range s {
if rune != previous {
result = append(result, rune)
}
previous = rune
}
return string(result)
}
Bear in mind that strings are UTF8 in Go so you have to use runes (characters) rather than bytes in order to be compatible with non-ASCII strings.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论