Reputation: 8468
How do I find out how many lines are in a string in Go?
Is there a builtin function, or do I have to "manually" search the string for all newlines +1?
Upvotes: 1
Views: 111
Reputation: 166598
For example,
package main
import (
"fmt"
"strings"
)
func NumLines(s string) int {
n := strings.Count(s, "\n")
if !strings.HasSuffix(s, "\n") {
n++
}
return n
}
func main() {
s := "line 1\nline 2\nline 3"
fmt.Println(NumLines(s))
}
Output:
3
Upvotes: 3