使用C++统计文本中字母出现次数及占比的技术实现问询
Hey there! Let's build a C++ program that counts how often each letter appears in a given text, calculates their percentage of the total letters, and finds the most frequent one. I'll walk you through the whole process with a clear example.
Approach
Here's the plan we'll follow:
- Normalize the text: Convert all letters to uppercase (or lowercase) so we count 'I' and 'i' as the same letter.
- Count occurrences: Use an array of size 26 (one for each letter A-Z) to keep track of how many times each letter appears.
- Calculate total letters: Sum up all valid letter counts to get the total number of letters in the text.
- Compute percentages: For each letter, divide its count by the total letters (as a floating-point number) to get the percentage.
- Find the most frequent letter: Iterate through our count array to find which letter has the highest count.
Complete C++ Code
#include <iostream> #include <string> #include <cctype> // For toupper() function using namespace std; int main() { // Initialize an array to hold counts for A-Z (index 0 = A, 1 = B, ..., 25 = Z) int letterCounts[26] = {0}; string inputText; int totalLetters = 0; // Get input text from the user cout << "Enter the text to analyze: "; getline(cin, inputText); // Iterate through each character in the text for (char c : inputText) { // Check if the character is a letter if (isalpha(c)) { // Convert to uppercase to normalize char upperC = toupper(c); // Calculate the index in the array (A = 65 in ASCII, so subtract 65) int index = upperC - 'A'; letterCounts[index]++; totalLetters++; } } // Check if there are any letters in the input if (totalLetters == 0) { cout << "No letters found in the input text." << endl; return 0; } // Display the count and percentage for each letter that appears cout << "\nLetter Frequency Analysis:\n"; for (int i = 0; i < 26; i++) { if (letterCounts[i] > 0) { char letter = 'A' + i; double percentage = (static_cast<double>(letterCounts[i]) / totalLetters) * 100; cout << "Letter " << letter << ": " << letterCounts[i] << " times (" << percentage << "%)\n"; } } // Find the most frequent letter int maxCount = 0; char mostFrequentLetter = ' '; for (int i = 0; i < 26; i++) { if (letterCounts[i] > maxCount) { maxCount = letterCounts[i]; mostFrequentLetter = 'A' + i; } } // Display the most frequent letter cout << "\nThe most frequent letter is: " << mostFrequentLetter << " (appeared " << maxCount << " times)\n"; return 0; }
Code Explanation
Let's break down what each part does:
- Normalization: We use
toupper()from<cctype>to convert every letter to uppercase. This ensures we don't count 'a' and 'A' separately. - Counting: The
letterCountsarray indexes correspond to each letter (0 = A, 1 = B, etc.). For each valid letter, we calculate its index by subtracting the ASCII value of 'A' from the uppercase character, then increment that index's count. - Total Letters: Every time we count a letter, we increment
totalLetters—this lets us calculate accurate percentages later. - Percentage Calculation: We cast the count to a
doublebefore dividing bytotalLettersto avoid integer division, then multiply by 100 to get a percentage. - Finding Most Frequent: We loop through the
letterCountsarray to track which index has the highest value, then convert that index back to a letter.
Example Output
If you input the sentence I stay in Ohio, here's what the program will output:
Enter the text to analyze: I stay in Ohio Letter Frequency Analysis: Letter A: 1 times (9.09091%) Letter H: 1 times (9.09091%) Letter I: 3 times (27.2727%) Letter N: 1 times (9.09091%) Letter O: 2 times (18.1818%) Letter S: 1 times (9.09091%) Letter T: 1 times (9.09091%) Letter Y: 1 times (9.09091%) The most frequent letter is: I (appeared 3 times)
内容的提问来源于stack exchange,提问作者Yahaya Ibrahim
相关产品推荐
相关产品推荐

