I've written a code that removes all vowels from a string in c but for some reason it doesn't remove the vowel 'o' for one particular input which is: zjuotps
here's the code:
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
cin >> s;
string a = "aeiouyAEIOUY";
for (int i = 0; i < s.length(); i ){
for(int j = 0; j < a.length(); j ){
if(s[i] == a[j]){
s.erase(s.begin() i);
}
}
}
cout << s;
return 0;
}
When I input: zjuotps
The Output I get: zjotps
CodePudding user response:
This is a cleaner approach using the C standard library:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string A = "zjuotps";
std::string S = "aeiouyAEIOUY";
auto pred = [&S](char c) { return S.find(c) != std::string::npos; };
auto it = std::remove_if(A.begin(), A.end(), pred);
A.erase(it, A.end());
cout << A << endl;
}
CodePudding user response:
You can develop a solution by adding the matching characters to the new string object. Otherwise, as @DrewDormann pointed out, there will be problems with consecutive vowels.
To solve this problem, I developed the eliminate() function. The eliminate() method writes the character to the result object if the characters in the input object doesn't match the characters in the remove object. The eliminate() function takes 3 parameters;
inputis the string object from which the characters to be removed will be scanned.removeis the string object containing the characters to be removed.resultis the string object containing the result data.
#include <iostream>
void eliminate(std::string input, std::string remove, std::string &result)
{
for (size_t i = 0; i < input.length(); i )
{
size_t j;
for(j = 0; j < remove.length(); j )
if(input[i] == remove[j])
break;
if(j == remove.length())
result = input[i];
}
}
int main()
{
std::string input = "zjuotpsUK", remove = "aeiouyAEIOUY", result;
eliminate(input, remove, result);
std::cout << result << std::endl;
return 0;
}
CodePudding user response:
This code is wrong because when you erase the element you have to take index back for next element
#include<iostream>
#include<string>
using namespace std;
int main(){
string s;
cin >> s;
string a = "aeiouyAEIOUY";
int i=0;
while ( i < s.length()){
for(int j = 0; j < a.length(); j ){
if(s[i] == a[j]){
s.erase(s.begin() i);
i--;
}
}
i ;
}
cout << s;
return 0;
}
