In Python I can iterate over a multiline string.
x = """\
this is
my multiline
string!"""
for line in x.splitlines():
print(line)
Can Go do the same?
If you need to iterate over each line of a string in Go (such as each line of a file), you can use the bufio.Scanner type which provides a convenient interface for reading data such as lines of text from any source.
To create or write multiline strings in Go, use the backtick (`) character while declaring or assigning value to the string. Multiline strings are very helpful when working with large strings like SQL, HTML or XML files inside Go. Please go through the below example to understand it further.
package main import "fmt" func main() { fmt.Println("Printing ") fmt.Println("multiline Strings ") fmt.Println("in Go!!") } Printing multiline Strings in Go!! Using backquote (`) character treats escape sequences such as , as a string literal and this allows us to write multi-line strings.
To iterate over the characters in a string, a for..range loop may be utilised. package main import "fmt" func main() { str := "I ♥ 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
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
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With