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.

GoData Integrity

Code

gosnippet
31 lines
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

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:`.