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.
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.
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.
 int isVowel(char ch)  
 {  
   ch = tolower(ch);  
   if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')  
     return 1;  
   return 0;  
 }  
 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--;  
     }  
   }  
 }  
Comments
Post a Comment