To split a string into lines and iterate over them in Go, you can use the strings.Split
function to split the string by newlines ("\n"
). Here's an example:
package main
import (
"fmt"
"strings"
)
func main() {
text := "Hello\nWorld\nGo\n"
lines := strings.Split(text, "\n")
for _, line := range lines {
fmt.Println(line)
}
}
This program splits the string text
into lines using strings.Split
, and then iterates over each line using a for range
loop. The range
loop provides the index and value of each line, but as we only need the value, we use the _
to ignore the index.
The above code will output:
Hello
World
Go
Note that the strings.Split
function will split the string at every occurrence of the separator ("\n" in this case), resulting in an empty line at the end. If you want to exclude empty lines, you can iterate over the lines and add a condition to skip empty lines:
package main
import (
"fmt"
"strings"
)
func main() {
text := "Hello\nWorld\nGo\n"
lines := strings.Split(text, "\n")
for _, line := range lines {
if line != "" {
fmt.Println(line)
}
}
}
Now, the output will be:
Hello
World
Go
This skips the empty line at the end of the string.