Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Program for the total number of words in a sentence

Posted on March 11, 2022March 11, 2022 by admin

Overview

Given a sentence find number of words in it. Each word in the sentence only has English letters

Example

Input: "Hello World"
Output: 2

Input: "This is hat"
Output: 3

Program

Here is the program for the same.

package main

import "fmt"

func countW(s string) int {

	lenS := len(s)
	numWords := 0

	for i := 0; i < lenS; {
		for i < lenS && string(s[i]) == " " {
			i++
		}

		if i < lenS {
			numWords++
		}

		for i < lenS && string(s[i]) != " " {
			i++
		}
	}

	return numWords
}

func main() {
	output := countW("Hello World")
	fmt.Println(output)

	output = countW("This is hat")
	fmt.Println(output)
}

Output

2
3
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme