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
Golang Slice vs Map Benchmark Testing
Get Year, Month, Day, Hour, Min and Second from current date and time.
Example: ReadAll, ReadDir, and ReadFile from IO Package
How to read current directory using Readdir?
How to verify a string only contains letters, numbers, underscores, and dashes in Golang?
How to handle HTTP Get response?