How to split a string by newline in Go

1 Answer

0 votes
package main

import (
	"bufio"
	"fmt"
	"strings"
)

// SplitByNewline takes a multi-line string and returns a slice of strings,
// automatically handling both Unix (LF) and Windows (CRLF) line endings.
// 
// @param s The input string to split.
// @return A slice of strings containing each individual line.
func SplitByNewline(s string) []string {
	var lines []string
	
	// Create a new reader from the input string and wrap it in a bufio.Scanner
	scanner := bufio.NewScanner(strings.NewReader(s))
	
	// Scan iterates line by line, stripping trailing newline characters automatically
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	
	return lines
}

func main() {
	// Sample text containing mixed line endings (Unix and Windows CRLF)
	multilineText := "Hello world!\nThis is line two.\r\nFinal line here."

	// Call the splitting function
	result := SplitByNewline(multilineText)

	// Print out the parsed lines
	for i, line := range result {
		fmt.Printf("Line %d: %s\n", i+1, line)
	}
}


/*
run:

Line 1: Hello world!
Line 2: This is line two.
Line 3: Final line here.

*/

 



answered 9 hours ago by avibootz
...