Function to remove all vowels from a string

I did come across a question "Write a program to remove all the vowels of a string in place"

Easy method would have been, copy all the characters to another string, except for vowels. But the restriction says in place. So you can not use another string.

Let us see how we can do it.
  • Extract one character of the string
  • If it is a vowel
    • start from character next to vowel. 
    • move all the characters to the left
    • also move null character to the left.
Now let us write functions
 int isVowel(char ch)  
 {  
   ch = tolower(ch);  
   if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')  
     return 1;  
   return 0;  
 }  
Function is simple enough. But why did we use tolower function. Just to avoid checking for capital letters. And note that since this parameter is call by value, the original character is not modified in the calling function.

 void shift_letters(char *s)  
 { 
  int i =0; int len = strlen(s);  s++;  
  for(i=1;i<len;i++,s++)  
  {  
   *(s-1)= *s;  
   }  
   *(s-1) = 0;  
 }  

 This function moves all characters to the left by one place.  Since we need to access all characters, I am using a safer way of repeating the loop len-1 times using i.

Now comes the actual function remove_vowels which inspects each character and if it is vowel removes it by calling shift_letters function.



 void remove_vowels(char *s)  
 {  
   int l = strlen(s);  
   for(;*s!='\0';s++)  
   {  
    if(is_vowel(*s))  
    {  
      shift_letters(s);  
      printf("%s\n",s);  
      s--;  
     }  
   }  
 }  
But if there are consecutive vowels, and once we remove one vowel, we need to check if the next character is again a vowel. So s is decremented after shifting the letters. If we had not used s--, only one vowel is removed in case of 2 consecutive vowels.




Comments

Popular Posts