Sling Academy
Home/Golang/Counting Occurrences of Characters and Words in Strings in Go

Counting Occurrences of Characters and Words in Strings in Go

Last updated: November 24, 2024

Counting occurrences of characters and words in strings is a common operation you might need when processing data, analyzing text, or performing other computational tasks. This article will guide you through the process using the Go programming language.

Basic Counting of Characters

Let's start by counting occurrences of individual characters in a string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world"
    charCount := map[rune]int{}

    for _, char := range str {
        charCount[char]++
    }

    for char, count := range charCount {
        fmt.Printf("%c: %d\n", char, count)
    }
}

In this example, we use a map to keep track of how many times each character appears in the string "hello world".

Intermediate Counting of Specific Characters

You can also tailor the character counting to focus on specific characters:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "abracadabra"
    specificChar := 'a'
    count := strings.Count(str, string(specificChar))
    
    fmt.Printf("The character '%c' appears %d times in \"%s\".\n", specificChar, count, str)
}

This code snippet demonstrates counting a specific character, in this case 'a', in the provided string using the strings.Count function.

Advanced Counting of Words

Moving on to counting words, which is bit more complex since words are separated by spaces. Here we'll count how often each word appears in a string:

package main

import (
    "fmt"
    "strings"
)

func main() {
    sentence := "go go go gophers are great gophers"
    words := strings.Fields(sentence)
    wordCount := map[string]int{}

    for _, word := range words {
        wordCount[word]++
    }

    for word, count := range wordCount {
        fmt.Printf("%s: %d\n", word, count)
    }
}

In this example, we utilize strings.Fields to split the sentence into words, then count each word's occurrence using a map.

Conclusion

We've explored different methods for counting characters and words in strings using Go. From basic character counting in a map to utilizing strings.Count for specific character occurrences, and finally counting complete words with the help of strings.Fields. With these methods, you should be well-equipped to handle text analysis tasks in your Go projects.

Next Article: Reversing a String in Go: Methods and Examples

Previous Article: Efficient String Manipulation with `strings.Builder` in Go

Series: Working with Strings in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant