Go中的Ruby squeeze替代方案是什么?

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

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.

huangapple
  • 本文由 发表于 2016年12月22日 22:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41285456.html
匿名

发表评论

匿名网友

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

确定