0

How do I find the percentage of characters in a text based on the users input.

Character Percentage

19th Aug 2017, 2:15 PM
Ade Omotayo
Ade Omotayo - avatar
4 Answers
+ 1
Sure, I did it in C++ though, I commented in case you don't know it + I didnt feel like posting in the playground :): #include <iostream> #include <array> int main() { // Array: A = index 0, B = index 1, ..., Z = index 25 std::array<int, 26> characters; characters.fill(0); // Counter int counter = 0; // String to process std::string s = "How do I find the percentage of characters in a text based on the users input?"; // for each char in s for(const auto& i : s) { // isalpha checks for alphabetic character if(isalpha(i)) { // Increment counter ++counter; // Convert all characters to uppercase, to create case insensitive // and since A = 65, we subtract 'A' to get the proper index. // 'Z' - 'A' would be 25 :) // and then increment that index by 1 ++characters[toupper(i) - 'A']; } } { int x = 0; // Iterate through the array for(const auto& i : characters) { // counter ? (true) : (false) = check if counter is anything but 0 // I have to convert the int to float to get floating point division // Anyway, divide the number by the counter and then * 100 = percentage float percentage = (counter ? static_cast<float>(i) / counter * 100 : 0); // Output std::cout << static_cast<char>(x++ + 'A') << ": " << percentage << '%' << std::endl; } } }
19th Aug 2017, 3:06 PM
Dennis
Dennis - avatar
+ 1
Now I understand. Thanks
19th Aug 2017, 3:40 PM
Ade Omotayo
Ade Omotayo - avatar
0
Lets say we want to keep track of a-z and don't care if they are upper or lowercase. 1. You will start with an array of 26 integers all initialized to 0 And another counter which keeps track of the total characters found. 2. You then iterate over the string and you check if the character is a character you want to check for and if it is you increment the corresponding index in the array and the counter by 1 3. You iterate over the array and divide the number by the total characters found ( beware of 0 division in edge cases ) and multiply that result by 100 to get the percentage. 4. Done :)
19th Aug 2017, 2:42 PM
Dennis
Dennis - avatar
0
A bit confused after instruction 2. Could you show that in code
19th Aug 2017, 2:52 PM
Ade Omotayo
Ade Omotayo - avatar