It's fine. But do not forget that if the last character is not a newline character, you need to add 1 to the number of occurrences, as this will be the number of lines (the last line may not end with a new line).
We might think that since the substring you are counting is only one character (one rune), we could create our own solution that takes into account only the appearance of this single character (instead of counting the substrings). It might look like this:
func countRune(s string, r rune) int {
count := 0
for _, c := range s {
if c == r {
count++
}
}
return count
}
(A for range string rune s.)
( Go Playground):
fmt.Println(countRune("asdf\nasdf\nasdf\n", '\n'))
, byte UTF-8 strings.Count() , 1:
func Count(s, substr string) int {
if len(substr) == 1 && cpu.X86.HasPOPCNT {
return countByte(s, byte(substr[0]))
}
return countGeneric(s, substr)
}
func countByte(s string, c byte) int
( ), "" , Text(), .