Reputation: 107
I've been trying to do this function where the target is to remove the vowels of a string. This is what I have :
void
take_vowels (char s[])
{
int i;
char r[4];
for (i = 0; i <= strlen (s); i++)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o'
|| s[i] == 'u')
{
r[i] = ' ';
}
else
{
r[i] = s[i];
}
}
printf ("%s\n", r);
}
int
main ()
{
char s[4] = { 'a', 'e', 'k', };
take_vowels (s);
return 0;
}
This seems to work fine but I want to know if there is a better way to do this function. Any suggestions?
Upvotes: 0
Views: 2092
Reputation: 1
int vowel(char ch)
{
if((ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')||
(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'))
return 1;
else
return 0;
}
void removevowel(char str[])
{
int count=0,i=0;
while(str[i]!='\0')
{
if(!vowel(str[i]))
{str[count++]=str[i];}
i++;
}
str[count]='\0';
}
int main()
{
char str[]="stAck overflOw SamplE";
removevowel(str);
for(int j=0; str[j]; j++)
cout<<str[j];
return 0;
}
Upvotes: 0
Reputation: 25129
Your title says 'remove vowels from the string', but in fact you are replacing the vowels by a space.
You don't need to do strlen
at all. You just need to remember that your string is (by definition) already large enough, and it is a sequence of characters. Also a switch
statement is nicer than a large if
, and you presumably want to handle both cases.
It's also normal to take a char *s
as an argument rather than a char s[]
. Look at every string function in the standard library! Similarly, the normal way to initialize C strings is:
char *s = "aek";
not
char s[4] = { 'a', 'e', 'k', };
Here's two (untested) functions which will help:
#include <ctype.h>
...
void
replacevowelsbyspace (char *s)
{
for (; *s; s++)
{
switch (tolower (*s))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
*s = ' ';
default:
break;
}
}
}
and
#include <ctype.h>
...
void
deletevowels (char *s)
{
char *d = s;
for (; *s; s++)
{
switch (tolower (*s))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
*d++ = *s;
}
}
*d = 0;
}
Upvotes: 0
Reputation: 311048
The problem with your function is that it has undefined behaviour because the source array can have more than 4 characters. The function does not remove vowels from the source string. It copies the source string in a local array replacing vowels with spaces.
So the function does not do what was announced.
Upvotes: 1