Skip to content
Advertisement

How to swap the first vowel and last vowel of a String using Java?

I am making a method called “Swap” where it takes in a string in the parameters. My goal is to swap the first and last vowel of the String. That’s it.

My way of finding this goes like this:

(fVowel is the index of the first vowel)

(lVowel is the index of the last vowel)

(newWord is a string declared above)

(firstVowel is a character from the first vowel)

(lastVowel is a character from the last vowel)

All of these have been done ^, just need the algorithm below to be accurate.

    for(int i = 0; i < s.length(); i++)
    {
   
        newWord += s.charAt(i);
        if(i == fVowel)
        {
            newWord += lastVowel;
        }
        if(i == lVowel)
        {
            newWord = s.substring(i-1, i);
            newWord += firstVowel;
            /*
            newWord.substring(i, i+1);
            newWord += firstVowel;
            */
        }

    }
    System.out.println(newWord);
    return newWord;
}

I am having trouble right now removing the character from the original string. I tried using substrings, but I can’t seem to have it figured out. Any help would be appreciated. Here’s an example of how it is suppose to work:

Main

swap("Red is rad");
swap("Hello Cats");

Output:

Rad is red
Hallo Cets

Advertisement

Answer

Your algorithm would work if you replace the part starting with newWord += s.charAt(i); with:

if(i == fVowel) {
  newWord += lastVowel;
} else if(i == lVowel) {
  newWord += firstVowel;
} else {
  newWord += s.charAt(i);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement