I'm doing a college assignment that asks for a program where the user types the string [20] and I return the inverted string and the vowels replaced by @s.
How do I do this?
I'm doing a college assignment that asks for a program where the user types the string [20] and I return the inverted string and the vowels replaced by @s.
How do I do this?
Well, I thought of this solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char vogais[] = {'a','A','e','E','i','I','o','O','u','U'};
char texto[20] = "stAckovErflow";
int i,j;
//substituindo as vogais
for(i=0; i < strlen(texto); i++)
{
for(j=0; j < strlen(vogais); j++)
{
if(vogais[j] == texto[i])
{
texto[i] = '@';
}
}
}
//invertendo a String
strrev(texto);
//imprimindo no console
printf("%s\n", texto);
system("pause");
return 0;
}
I hope I have helped!
Strings in C are character arrays. Use for
with a i
counter to move through each position. At each iteration of for
, you get the letter at the i
position and compare it with 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
. If one of these comparisons is true (use ||
), then you change the character in the string by a '@'
. You will have to compare both the lower and upper case vowels.
After you use another for
to invert the string, it will go through i
positions from the beginning of the string to the middle, then you change the character from the i
to the n - i - 1
position, where n
is the length of the string.
To replace the vowels with '@', we go through array of characters (str), for each character check if it is equal to a vowel (str [i] == vowels [v]), assigning the @ in the index which is the vowel (str [i] = '@')
In the example below, the result is 'st @ ck @ v @ rfl @ w' for str="stackoverflow";
int main()
{
char vogais[] = {'a','e','i','o','u'};
char str[20] = "stackoverflow";
for(int i =0; i<strlen(str); i++){
int vogal=0;
for(int v =0; v<5; v++){
if(str[i] == vogais[v]) vogal= 1;
}
if(vogal == 1){
str[i] = '@';
}
}
printf("%s",str);
return 0;
}