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, "\n")
if !strings.HasSuffix(s, "\n") {
n++
}
return n
}
func main() {
s := "line 1\nline 2\nline 3"
fmt.Println(NumLines(s))
}
Output:
3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.