How to count the occurrences of a word in a string using Go

1 Answer

0 votes
package main

import (
	"fmt"
	"strings"
)

func countOccurrences(str, word string) int {
	// Convert both str and word to lowercase to make the search case-insensitive
	str = strings.ToLower(str)
	word = strings.ToLower(word)

	// Split the str into words
	words := strings.Fields(str)

	count := 0

	// Iterate through the words and count the occurrences of the target word
	for _, w := range words {
		if w == word {
			count++
		}
	}

	return count
}

func main() {
	str := "Go is a high-level general purpose programming language Go is statically typed and compiled"
	word := "go"
	
	count := countOccurrences(str, word)
	
	fmt.Printf("The word '%s' occurs %d times\n", word, count)
}



/*
run:
     
The word 'go' occurs 2 times

*/
 

 



answered Feb 28, 2025 by avibootz
edited Mar 1, 2025 by avibootz
...