Wednesday, December 28, 2022
A function, given a string s
, to return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
func countSegments(s string) int {
trimmedS := strings.Trim(s, " ")
length := len(trimmedS)
if length == 0 {
return 0
}
var segmentsNumber int
for idx, rune := range trimmedS {
// skip last character
if (idx+1 == length) {
continue
}
nextRune := trimmedS[idx+1]
// count only if next character is not whitespace
if string(rune) == " " && string(nextRune) != " " {
segmentsNumber++
}
}
return segmentsNumber+1
}