Introduction
A Frequency Counter is a program that helps us count how many times each character appears in a string. This is a very common task in programming, especially in text analysis, data processing, and natural language processing tasks. The goal of this program is to analyze a given string and output the frequency of each character present in the string.
In this tutorial, we will be using the Go programming language to create a frequency counter. The program will take a string input from the user and return the count of each character that appears in the string.
Objective
The objective of this program is to:
- Accept a string input from the user.
- Count the frequency of each character in the string.
- Display the frequency count of each character in the string.
Go Program Code
package main
import (
"fmt"
)
func main() {
// Ask the user for input
fmt.Print("Enter a string: ")
var input string
fmt.Scanln(&input)
// Create a map to store frequency of each character
freqMap := make(map[rune]int)
// Loop through each character in the string and update its frequency
for _, char := range input {
freqMap[char]++
}
// Display the frequency of each character
fmt.Println("Character frequencies:")
for char, count := range freqMap {
fmt.Printf("%c: %d\n", char, count)
}
}
Explanation of the Program Structure
Let’s break down the code step by step:
- Importing Packages: We import the
fmt
package, which provides functions for formatted I/O operations such as printing text to the console. - Taking User Input: The
fmt.Print
function asks the user to input a string. We then usefmt.Scanln
to store the input string in the variableinput
. - Creating a Frequency Map: We use a map
freqMap
where the key is a rune (character), and the value is an integer representing the frequency of that character. - Counting Frequencies: The
for
loop iterates over the string and updates the frequency map. Therange
keyword helps us iterate through each character (rune) in the string. - Displaying Results: Another
for
loop is used to print the frequency of each character present in the string usingfmt.Printf
.
How to Run the Program
- Install Go programming language from the official website: Go Downloads.
- Save the code in a file with a
.go
extension (for example,frequency_counter.go
). - Open the terminal or command prompt and navigate to the folder where the file is saved.
- Run the program by typing the following command in the terminal:
go run frequency_counter.go
- After running the program, input a string when prompted, and the program will output the frequency of each character in the string.