Replace vowel with next does not work

Venky

I have a string input and want to replace every vowel in that string with its next vowel.

However, it does not seem to work correct. I have tried various input like:

venky -> vinky // Correct
ui    -> uo    // Incorrect, expected ao
ai    -> ao    // Incorrect, expected eo

The vowel order is

char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

My code is:

package test;
import java.util.Scanner;

public class Problem1 {
    public static void main(String args[]) {
        Scanner r = new Scanner(System.in);
        String str, res;
        char ch;
        int i, j;
        char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

        System.out.println("Enter a string");
        str = r.nextLine();
        res = str;

        for (i = 0; i < str.length(); i++) {
            ch = str.charAt(i);

            for (j = 0; j < 4; j++) {
                if (ch == 'u') {
                    res = str.replace(ch, 'a');
                    break;
                } else if (ch == vowels[j]) {
                    res = str.replace(ch, vowels[j+1]);
                    break;
                }
            }
        }

        System.out.println("String after replacing the vowels with next vowel : "
            + res);
    }   
}
StephaneM

Your problem is here:

res = str.replace(ch, vowels[j+1]);

Consider the input ai. The 1st time you pass here you change the value of res to ei, the second time you replace the i in the initial string ai, not in the modified one. So res gets the new value ao.

Anyway, even if you fix this particular case you may hit some other issue with longs words containing many wovels as you replace the first occurence (imagine the case of ae you would get ie). You should build the result one char at a time, with either the unmodified letter or the next wovel.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive