Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strings.Split on newline?

Tags:

go

People also ask

How do you split a string into a newline in Python?

To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of a newline, "\n" .

How do you separate a new line in Java?

2.2.The “\n” character separates lines in Unix, Linux, and macOS. On the other hand, the “\r\n” character separates lines in Windows Environment. Finally, the “\r” character separates lines in Mac OS 9 and earlier.

What is delimiter for New line?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


You have to use "\n".

Splitting on `\n`, searches for an actual \ followed by n in the text, not the newline byte.

playground


For those of us that at times use Windows platform, it can help remember to use replace before split:

strings.Split(strings.ReplaceAll(windows, "\r\n", "\n"), "\n")

Go Playground


It does not work because you're using backticks:

Raw string literals are character sequences between back quotes ``. Within the quotes, any character is legal except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines.

Reference: http://golang.org/ref/spec#String_literals

So, when you're doing

strings.Split(result,`\n`)

you're actually splitting using the two consecutive characters "\" and "n", and not the character of line return "\n". To do what you want, simply use "\n" instead of backticks.


Your code doesn't work because you're using backticks instead of double quotes. However, you should be using a bufio.Scanner if you want to support Windows.

import (
    "bufio"
    "strings"
)

func SplitLines(s string) []string {
    var lines []string
    sc := bufio.NewScanner(strings.NewReader(s))
    for sc.Scan() {
        lines = append(lines, sc.Text())
    }
    return lines
}