(C) Make an algorithm that reads a string and removes vowels and whitespace

Asked

Viewed 704 times

0

The code is copying ALL characters from one string to the other and ignoring the copy condition. I know there is an easier way to remove spaces and vowels, which is to bring the next character to the current position, but it was requested that the code be made this way.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Faça um algoritmo que leia uma string e remova as vogais e os espaços em 
branco. */

int main(int argc, char *argv[]) {
system ("color 0a");
char str[1000], newstr[1000];
int i = 0;
printf ("Insira uma string:\n");
gets(str); 
while (str[i] != '\0'){
    if (str[i] != 'a'||str[i] != 'e'||str[i] != 'i'||str[i] != 'o'||str[i] 
!= 'u'){
        newstr[i] = str [i];
    }else{
            if (str[i] != 'A'|| str[i] != 'E'|| str[i] != 'I'|| str[i] != 
'O'|| str[i] != 'U'){
                newstr[i] = str [i];
        }else{
                    if (str[i] != ' '){
                        newstr[i] = str [i];
            }
        }       
    }
    i++;
}
printf ("String sem vogais:\n");
puts (newstr);
system ("pause");
return 0;
}

1 answer

1


 int i = 0, x=0;
    printf ("Insira uma string:\n");
    fgets(str, 999, stdin);     
    while (str[i] != '\0')
    {
        if (str[i] == 'a'||str[i] == 'e'||str[i] == 'i'||str[i] == 'o'||str[i]== 'u' || str[i] == 'A'|| str[i] == 'E'|| str[i] == 'I'|| str[i] =='O'|| str[i] == 'U')
        {
            i++;
            continue;
        }
        else
        {
            if (str[i] != ' ')
            {
                newstr[x++] = str [i];
            }
        }
        i++;
    }

I made these little changes, put it all on one line if, if it’s the same then it does nothing, continue.

Another important step is to use the newstr[x++] because in doing newstr[i]. Ex: fabio

What you’re gonna do is you’re gonna put it in position 0 f and then put into position 2 b ...

That is to say, newstr would look something like f_b and in that space can come any character.


  • Never do gets(str);, swap for fgets(str, 999, stdin);, because with the gets if the user inserts a string larger than 1000 breaks the program.

Code in the Ideone

  • 1

    I read these days about gets, that it was a bit problematic because it does not limit the memory space allocated by the variable and also that the command "continue" skips the rest of the code below in the loop and jumps to next iteration. Thanks even, it worked perfectly here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.