DEV Community

RATHEESH G KUMAR
RATHEESH G KUMAR

Posted on

πŸ’‘ Character Frequency Count in a String using Goroutines in Go

In Go, strings are immutable, meaning once a string is created, its value cannot be modified directly. However, we can still analyze and process strings efficiently.

In this example, we will implement a program to calculate the frequency of each character in a string using Goroutines and channels.

πŸ”€ Sample String:

`str := "We often will need to manipulate strings in our messaging app. For example, adding some personalization by using a customer's name within a template"`
Enter fullscreen mode Exit fullscreen mode

πŸ“¦ Step 1: Define a Struct to Hold Character and Count

type CharFreq struct {
Char rune
Count int
}

πŸ“¦ Step 2: Declare a Map and Channel


charCh := make(chan CharFreq)
strMap := make(map[string]int)
Enter fullscreen mode Exit fullscreen mode

πŸ” Step 3: Iterate Through the String and Count Characters
We will convert all characters to lowercase and ignore spaces and punctuation.


`for _, v := range str {
    // Convert uppercase to lowercase
    if v >= 'A' && v <= 'Z' {
        v += 32
    }

    // Skip spaces and punctuation (optional enhancement)
    if v == ' ' {
        continue
    }

    // Convert rune to string and count
    strMap[v]++
}`
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Step 4: Use an Anonymous Goroutine to Send Data to Channel

`go func() {
    for i, v := range strMap {
        charCh <- CharFreq{Char: i, Count: v}
    }
    close(charCh)
}()`
Enter fullscreen mode Exit fullscreen mode

πŸ“€ Step 5: Read from Channel and Print Results


`for item := range charCh {
    fmt.Printf("Character: %s, Count: %d\n", item.Char, item.Count)
}`

Enter fullscreen mode Exit fullscreen mode

βœ… Final Output:
You will get the frequency of each character (excluding spaces) printed via the channel using a concurrent approach.

//output
Character: g, Count: 5
Character: x, Count: 1
Character: e, Count: 14
Character: o, Count: 8
Character: m, Count: 7

Complete implementation link: https://www.programiz.com/online-compiler/0G4nsPTV0NR3B

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay