In my project I take a string from user and then I need to check if vowels a, e, I, O, U are present. If so, I have to find out which one comes first in the string and which one comes next after that. For example, if a user gave input something like this:
char expr[] = "this is for something real";
I comes first, then I again, then O and so on. I checked whether the characters are in the string or not using strchr(expr,'character here'). To find which character comes first, I find the index of each character using
const char *ptr = strchr(expr, characters here);
if(ptr) {
int index = ptr - expr;
}
After that I check which index is bigger. But this is very long process.
Is there a smarter way to do this?
If you don’t need the locations in the original string, but only the order, you can use
std::remove_copy_ifwith a functor that detects non-vowel characters (i.e. returns true for vowels):(Using C++11 features to obtain the iterators and a lambda instead of creating a functor, but the same can be written in C++03 with a bit of extra boiler plate code. Code is untested)
After the algorithm completes,
only_vowelswill contain only the vowels present in the original string and in the exact order where they appeared. Case is not modified by the algorithm.Alternatively you can iterate manually over the elements in the string, and test each character to see whether it is a vowel, then print it or do whatever needs to be done. If this is homework, this is probably what is expected from you.