Home > Mobile >  Replace consonants with previous letter and vowels with next letter in a String
Replace consonants with previous letter and vowels with next letter in a String

Time:03-06

I'm a beginner in C. I'm trying to make a program that changes the vowels with the next letter in the alphabet, and the consonants with the previous letter. I would be happy if you could help me. Here is my code:

#include <stdio.h>
#include <string.h>

void modifyString( char vovels[], char string[]){
    for(int i = 0; i < strlen(string); i  ){
        for(int j = 0; j < strlen(vovels); j  ){
            if(string[i] == vovels[j]){
                (char)(string[i]  = 1);
            } else if((string[i] >= 'a' && string[i] <= 'z')){
                (char)(string[i]-= 1);
            }
        }
    }
    printf("%s ",string);
}

int main() {

    char vov[]="aeiou",str[100];

    printf("String is : ");
    gets(str);
    strlwr(str);
    modifyString(vov,str);
    return 0;
}

CodePudding user response:

You are not far off. You can just loop over the strings without calling strlen(), for example iterating with for (int i = 0; string[i]; i ) which will increment i until it points to the nul-terminating character at the end of string which is ASCII '\0' and has the value of plain-old 0. The loop in str2lower() (below) does the exact same thing except it iterates with a pointer instead of an index.

Your logic in modifyString() looks fine, but you should not cast (char) when incrementing the values. There is no need. You can simplify your logic by letting strchr() check if the current char is one of the characters in vowles with if (strchr (vowels, string[i])) eliminating the j loop altogether.

It's unclear where strlwr(str); is defined, but you can write a simple string to lower easy enough.

Also in my comment, you never, ever, ever use gets() or use scanf() with "%s" without using the field-width modifier (e.g. "

  •  Tags:  
  • c
  • Related