How to split a string based on change of characters in Go

1 Answer

0 votes
package main
 
import (
    "bytes"
    "fmt"
)
 
func main() {
    s := `aaabbbcccdddqqq`
    if len(s) < 2 {
        fmt.Println(s)
    }
    var buf bytes.Buffer
    ascii := s[0]
 
    buf.WriteByte(ascii)
    for _, asciinext := range []byte(s[1:]) {
        if asciinext != ascii {
            buf.WriteString("\n")
        }
        buf.WriteByte(asciinext)
        ascii = asciinext
    }
    fmt.Println(buf.String())
}




/*
run:

aaa
bbb
ccc
ddd
qqq

*/

 



answered Aug 26, 2020 by avibootz
...