boykott
boykott

Reputation: 21

replace vowels with the character following it

I'm trying to write a Java program in which it takes an input and replaces all the vowels with the character following it.

For example:

starcraft --> strrcrfft
parker --> prrkrr

This is what I have so far.

import java.util.Scanner;

public class Vowelconverter {

    public static void main(String[] args) {

        Scanner myInput = new Scanner(System.in);
        System.out.println("Enter your string here: ");
        String myString = myInput.nextLine();
        String test = "";
        char vowels [] = {'a','e','i','o','u'};

        for (int i = 0; i <= myString.length(); i++){
            if (myString.charAt(i) == vowels[0] || myString.charAt(i) == vowels[1] || myString.charAt(i) == vowels[2] || myString.charAt(i) == vowels[3] || myString.charAt(i) == vowels[4]){       
                test = test + myString.charAt(i+1);
            }   
        }


        System.out.println(myString);
        System.out.println(test);
    }

}

Upvotes: 2

Views: 6985

Answers (3)

Autumn
Autumn

Reputation: 3756

MrFred's answer is a good one, but only works on vowels followed by non-vowels. The more general (java) answer is

   myString = myString.replaceAll("[aeiouy](.)","$1$1" );

Do learn regex, it's extremely powerful. The statement above is an extremely terse way of saying:

  1. A match consists of a single character from this range (of vowels), followed by a subexpression comprising any single character.

  2. Replace every match with two instances of the first subexpression ($1) from the match.

Upvotes: 1

mfred
mfred

Reputation: 187

This is typically the kind of task where regular expressions are helpful. Here is a basic one that solves your problem:

s/[aeiouy]([^aeiouy])/$1$1/g

Upvotes: 1

Mike Nakis
Mike Nakis

Reputation: 62045

  • Use descriptive identifiers, like inputString and outputString; things like myString and test are unacceptable.

  • Use a String for your vowels instead of a char[], so that you can do vowels.indexOf( character ) != -1 to check if the character is a vowel, instead of that loooooong if statement.

  • Do not loop until the very end of the string; loop until myString.length() - 1, otherwise myString.charAt(i+1); will attempt to access a character beyond the end of the string. After the loop is done, add the last character of the input string to the output string without checking if it is a vowel, because even if it is, there is nothing you can replace it with.

  • To solve your main problem, (not building the output string properly,) consider this: on each iteration of the loop, you must be appending a character to the output string. You cannot be only appending a character under certain conditions, because if you do that, then some characters from the input string will never make it to the output string.

Upvotes: 0

Related Questions