Skip to content

Instantly share code, notes, and snippets.

@manigandand
Created November 19, 2019 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manigandand/4647d34c392775e5b733cf02f6880b46 to your computer and use it in GitHub Desktop.
Save manigandand/4647d34c392775e5b733cf02f6880b46 to your computer and use it in GitHub Desktop.
find words count in a given string
// To execute Go code, please declare a func main() in a package "main"
package main
import (
"fmt"
// "strings"
)
// countWords returns the count of words in a given string
func countWords(s string) int{
var (
count,wordFlag int
previousRuneValue rune
)
// NOTE: I introduced a new flag(exclude), instead of Continuing to the next pointer
// i set the flag to TRUE on the validation error, and i make sure to increment the
// only upon exclude flag is FALSE.
for i, w := range s{
var exclude bool
if w == 32 && previousRuneValue == 32 {
exclude = true
}
if (w == 32 && i == 0) || (w == 32 && i == len(s)-1){
exclude = true
}
if w == 32 && !exclude{
count++
wordFlag = 0
}
previousRuneValue = w
wordFlag = 1
}
// wordList := strings.Split(strings.TrimSpace(s), " ")
// for _, w := range wordList {
// if strings.TrimSpace(w) != ""{
// count++
// }
// }
return count + wordFlag
}
func main() {
input := " hello world 123"
fmt.Println("Word Count: ",countWords(input))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment