Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over multiline string in Go

Tags:

go

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?

like image 788
Duke Dougal Avatar asked Oct 16 '15 04:10

Duke Dougal


People also ask

How to iterate over each line of a string in go?

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.

How to create or write multiline strings in go?

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.

How to print multi-line strings in Golang?

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.

How to iterate over the characters in a string in Python?

To iterate over the characters in a string, a for..range loop may be utilised. package main import "fmt" func main() { str := "I ♥ Go!"


3 Answers

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

like image 142
Ben Campbell Avatar answered Oct 20 '22 06:10

Ben Campbell


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
}
like image 43
Bayta Darell Avatar answered Oct 20 '22 04:10

Bayta Darell


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

like image 26
Zombo Avatar answered Oct 20 '22 05:10

Zombo