Split a character string based on change of character
Here's an example program that splits a (character) string into new line based on a change of character or space.
strBuf is a variable-sized buffer of bytes with Read and Write methods.
WriteString
appends the contents of strBuf to the buffer, growing the buffer as needed.Using a for loop we write the content to
strBuf
and line break "\n" added on change of a character in str string.The final piece of our program
fmt.Println(strBuf.String())
is used to display the output.
Example
package main
import (
"bytes"
"fmt"
)
func main() {
str := `aaaabbbbccccddddeee\\\\2222 mmmm,88888`
if len(str) < 2 {
fmt.Println(str)
}
var strBuf bytes.Buffer // A Buffer needs no initialization.
indx := str[0]
strBuf.WriteByte(indx)
for _, count := range []byte(str[1:]) {
if count != indx {
strBuf.WriteString("\n")
}
strBuf.WriteByte(count)
indx = count
}
fmt.Println(strBuf.String())
}
Output
aaaa
bbbb
cccc
dddd
eee
\\\\
2222
mmmm
,
88888
Most Helpful This Week
Convert Float32 to Float64 and Float64 to Float32
Example of Switch Case with Break in For Loop
Regular Expression to get a string between parentheses in Golang
Converting Int data type to Float in Go
How to use wildcard or a variable in our URL for complex routing?
Various examples of printing and formatting in Golang
Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]
Example: Stack and Caller from RUNTIME package
URL parser in Golang
How to convert Colorful PNG image to Gray-scale?