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?
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?
For example,
package main
import (
"fmt"
"strings"
)
func NumLines(s string) int {
n := strings.Count(s, "
")
if !strings.HasSuffix(s, "
") {
n++
}
return n
}
func main() {
s := "line 1
line 2
line 3"
fmt.Println(NumLines(s))
}
Output:
3