'remove duplicate characters immediately following one another

I am trying to remove duplicate characters that are immediately following each other.

E.g. "Whyyyy sooo ssserioooouuussss" should translate to "Why so serious"

In PHP PCRE this is possible like this

$text = preg_replace("/(.)\\1+/", "$1", $text);

I tried to do following

var duplicateRegex = regexp.MustCompile(`(?P<char>.)${char}+`)
text = duplicateRegex.ReplaceAllString(text, `${char}`)

Test on play.golang.com

but it does not seems to work in go. Any ideas? Thank you

go


Solution 1:[1]

Try the following code. It ranges over the string rune by rune. If the rune is different from the last or it's the first rune, then add the rune to the result.

func removeDups(s string) string {
    var buf bytes.Buffer
    var last rune
    for i, r := range s {
        if r != last || i == 0 {
            buf.WriteRune(r)
            last = r
        }
    }
    return buf.String()
}

In Go 1.10, the bytes.Buffer can be replaced with strings.Builder to minimize allocations.

Solution 2:[2]

Try this:

str := "Whyyyy sooo ssserioooouuussss ?????"
fmt.Println(str)
var buf bytes.Buffer
var pc rune
for i, c := range str {
    if i ==  0{
        pc = c
        buf.WriteRune(c)
    }

    if pc == c {
        continue
    }

    pc = c
    buf.WriteRune(c)
}
fmt.Println(buf.String())

Result:

Whyyyy sooo ssserioooouuussss ?????
Why so serious ???

Solution 3:[3]

str := "Whyyyy sooo ssserioooouuussss"

var last rune

var sb strings.Builder

for _, r := range str {
    if r != last {
        sb.WriteRune(r)
        last = r
    } else {
        continue
    }
}

fmt.Println(sb.String())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Cooper
Solution 2
Solution 3