Problem 2: Replace all vowels in sentence by the underscore character.
In this program, you ask user to enter a sentence and read it using string class function getline. Use a for loop to iterate through all characters. Please use str.at(i) method to access each string character. If a character is a vowel, replace it with ’ ’. Both upper and lower case vowels have to be replaced. Those who use an array for string are going to lose points as char.at(i) verifies that the character position in a string is valid. Example run:
Please enter a sentence:
Hello There!
You entered the sentence "Hello There!"
Your sentence after replacing vowels by underscores is H_ll_ Th_r_!
#include <iostream>
#include <string>
using namespace std;
int main(){
string inputString;
string outputString;
cout<<"Please enter a sentence:\n";
getline(cin,inputString);
//a for loop to iterate through all characters.
// use str.at(i) method to access each string character. If a character is a vowel, replace it with ’ ’. Both upper and lower case vowels have to be replaced.
string vowels = "AEIOUY";
outputString=inputString;
for (int i = 0; i < inputString.size(); i++){
for (int j = 0; j < vowels.size(); j++)
{
if (toupper(inputString.at(i)) == vowels.at(j))
{
outputString.at(i)='_';
break;
}else{
outputString.at(i)=inputString.at(i);
}
}
}
//display sentence after replacing
cout<<"You entered the sentence \""<<inputString<<"\"\n";
cout<<"Your sentence after replacing vowels by underscores is "<<outputString<<"\n";
system("pause");
return 0;
}
Comments
Leave a comment