Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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

Related questions

...