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"`
π¦ 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)
π 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]++
}`
βοΈ 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)
}()`
π€ Step 5: Read from Channel and Print Results
`for item := range charCh {
fmt.Printf("Character: %s, Count: %d\n", item.Char, item.Count)
}`
β
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
Top comments (0)