strings.SplitAfter extra empty slice element?

Is the below code expected behaviour with strings.SplitAfter?
I would expect (and think it more helpful) if it returned just the 2 slice elements?
Sorry if a dumb simple question but I couldn’t seem to find a similar question or definitive answer

Thanks
sheddy

package main

import “fmt”
import “strings”

func main() {
text := “line0\nline1\n”
lines := strings.SplitAfter(text, “\n”)
fmt.Println(len(lines))
}

3

Program exited.

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

So from that snippet, I’d expect a slice with line0 and line1, both ending with a newline and also a third empty string, as that is what comes after the second newline in the original string.

Also, if you would like to only have ["line0\n" "line1\n"], you can pass the result of strings.SplitAfter into a function like:

func removeEmptyStringsInplace(ss []string) []string {
	for i := len(ss) - 1; i >= 0; i-- {
		if ss[i] == "" {
			copy(ss[i:], ss[i+1:])
			ss = ss[:len(ss)-1]
		}
	}
	return ss
}

Which should remove all the blank strings from the slice you pass in.

Thanks guys, I see that help snippet can be interpreted that way even if there aren’t any strings after the separator to become a substring. Will bear in mind adjusting to the off by 1s which GO is usually quite friendly to avoid or try something like in your suggestion. Cheers

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.