Iterate over multiline string in Go
You can use bufio.Scanner
in Go which iterates over lines from an io.Reader
. The following example creates a reader from the given multiline string and passes it to the scanner factory function. Each invocation of scanner.Scan()
splits the reader on the next line and buffers the line. If there is no more lines it returns false. Calling scanner.Text()
returns the buffered split.
var x string = `this is
my multiline
string`
scanner := bufio.NewScanner(strings.NewReader(x))
for scanner.Scan() {
fmt.Println(scanner.Text())
}
In the example, the for loop will continue until Scan()
returns false at the end of the multiline string. In each loop we print the line returned by the scan.
https://play.golang.org/p/U9_B4TsH6M
I think using bufio
is the best option, but if you do need to just split a
string, I think TrimRight
is better than TrimSuffix
, as it could cover any
combination of repeated trailing newlines or carriage returns:
package main
import "strings"
func main() {
x := `this is
my multiline
string!
`
for _, line := range strings.Split(strings.TrimRight(x, "\n"), "\n") {
println(line)
}
}
https://golang.org/pkg/strings#TrimRight
If you want to iterate over a multiline string literal as shown in the question, then use this code:
for _, line := range strings.Split(strings.TrimSuffix(x, "\n"), "\n") {
fmt.Println(line)
}
Run the code on the playground
If you want to iterate over data read from a file, use bufio.Scanner. The documentation has an example showing how to iterate over lines:
scanner := bufio.NewScanner(f) // f is the *os.File
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
// handle error
}