Filtering Vowels and Formatting Consonants in Strings
The task requires processing an input string to remove all vowel characters (A, O, Y, E, U, I in both upper and lower case) and then format the remaining consonant characters. The formatting involves prefixing each consonant with a period ('.') and converting the character to its lowercase form. The algorithm must guarantee a non-empty output string.
The core algorithm is as follows:
- Define a set containing all target vowel characters, accounting for case sensitivity.
- Iterate through each character in the input string.
- For each character, check if it exists in the vowel set.
- If its a vowel, discard it.
- If it is a consonant, append a '.' character followed by the lowercase version of the consonant character to the result string.
- After processing all characters, the constructed result string is the final output.
The following C++ code implements this logic:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string inputStr, outputStr;
// Read the input string
getline(cin, inputStr);
// Define vowel characters (upper and lower case)
string vowels = "AaOoYyEeUuIi";
// Process each character in the input
for (char ch : inputStr) {
// Check if the character is a vowel
if (vowels.find(ch) != string::npos) {
// Skip vowels
continue;
} else {
// For consonants, add a dot and the lowercase character
outputStr.push_back('.');
outputStr.push_back(tolower(ch));
}
}
// Output the final processed string
cout << outputStr << endl;
return 0;
}
Key components of the code:
getline(cin, inputStr): Reads a line of input, which can handle strings with spaces.cin >> inputStrwould stop at whitespace.string vowels: A string serving as a set of characters to identify vowels.for (char ch : inputStr): A range-based for loop that iterates over each characterchininputStr.vowels.find(ch) != string::npos: Checks if the characterchexists within thevowelsstring.string::nposis a constant representing 'not found'.outputStr.push_back('.'): Appends a period to the end of the result string.outputStr.push_back(tolower(ch)): Appends the lowercase version of the consonant character. Thetolowerfunction from<cctype>handles the case conversion.cout << outputStr << endl;: Prints the final formatted string.