Alasdair
Alasdair

Reputation: 14151

How to strings.Split on newline?

I'm trying to do the rather simple task of splitting a string by newlines.

This does not work:

temp := strings.Split(result,`\n`)

I also tried ' instead of ` but no luck.

Any ideas?

Upvotes: 88

Views: 107768

Answers (6)

Ilia Choly
Ilia Choly

Reputation: 18557

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
}

Alternatively, you can use strings.FieldsFunc (this approach skips blank lines)

strings.FieldsFunc(s, func(c rune) bool { return c == '\n' || c == '\r' })

Upvotes: 14

czerny
czerny

Reputation: 16682

import regexp

var lines []string = regexp.MustCompile("\r?\n").Split(inputString, -1)

MustCompile() creates a regular expression that allows to split by both \r\n and \n

Split() performs the split, seconds argument sets maximum number of parts, -1 for unlimited

Upvotes: 4

Cameron
Cameron

Reputation: 3083

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

Upvotes: 49

Jess
Jess

Reputation: 122

' doesn't work because it is not a string type, but instead a rune.

temp := strings.Split(result,'\n')

go compiler: cannot use '\u000a' (type rune) as type string in argument to strings.Split

definition: Split(s, sep string) []string

Upvotes: -3

OneOfOne
OneOfOne

Reputation: 99381

You have to use "\n".

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

playground

Upvotes: 118

julienc
julienc

Reputation: 20355

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.

Upvotes: 21

Related Questions