红宝石压缩替代
问题描述:
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?
答
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.