Strings Lines Iterator
Iterate over a string with strings.Lines and see how each yielded value keeps its line terminator, including CRLF input and an empty line.
Code
package main
import (
"fmt"
"strings"
)
func main() {
text := "alpha\nbeta\r\n\ngamma"
// strings.Lines returns an iterator that yields each line with its terminator
count := 0
for line := range strings.Lines(text) {
count++
fmt.Printf("%d %q\n", count, line)
}
fmt.Println("lines:", count)
// Windows and Unix terminators both stay inside the yielded values
for line := range strings.Lines("one\r\ntwo\n") {
fmt.Println("ends with newline:", strings.HasSuffix(line, "\n"))
}
// a trailing terminator does not produce an extra empty line
trailing := 0
for range strings.Lines("x\n") {
trailing++
}
fmt.Println("trailing terminator lines:", trailing)
fmt.Println("newline count:", strings.Count(text, "\n"))
}How it works
Strings Lines Iterator reduces to the function main.
for line := range strings.Lines(text) is the loop that carries the per-item work.
Caveats
- Self-contained — no imports beyond what the runtime already provides.
Using it
Running the file prints labeled results such as lines:, ends with newline:, trailing terminator lines: — each operation’s effect is visible in the output.
Key statements
for line := range strings.Lines("one\r\ntwo\n") {
fmt.Println("ends with newline:", strings.HasSuffix(line, "\n"))
}
for line := range strings.Lines(text) {
count++
fmt.Printf("%d %q\n", count, line)
}
for range strings.Lines("x\n") {
trailing++
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Strings Lines Iterator print when run?
- Execute the whole file; each printed line is prefixed with a label like `lines:`, `ends with newline:`, `trailing terminator lines:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.