lapartman
lapartman

Reputation: 75

How do I create a method that adds a dash after every vowel?

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

    public static String insertDashAfterWovel(String input){

    char[] tmp=input.toCharArray();

    for (int i = 0; i < tmp.length; i++) {
        if (tmp[i]== vowelArray[i]){
            tmp[i]+='-';
            return tmp.toString();
        }
    }
    return "";

The method I made doesn't work. How do I make it so that it adds a dash after every detected vowel and returns the string like in the example below? I made a testclass for this method to verify whether I'm right.

"gladiator" should return "gla-di-a-to-r"

Upvotes: 0

Views: 491

Answers (5)

Abu Sulaiman
Abu Sulaiman

Reputation: 1507

Since the poster's question is:

The method I made doesn't work. How do I make it so that it adds a dash after every detected vowel and returns the string like in the example below? "gladiator" should return "gla-di-a-to-r"

I am providing a working example that most closely resembles the original method.

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

public static String insertDashAfterVowel(String input){

    char[] tmp=input.toCharArray();
    String newString = "";
    for (int i = 0; i < tmp.length; i++) {
        newString += tmp[i];
        if (new String(vowelArray).indexOf(tmp[i]) != -1){
            newString += "-";            
        }
    }
    return newString;
}

Upvotes: 1

rehan
rehan

Reputation: 489

Try this:

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

 public static String insertDashAfterWovel(String input){

    char[] tmp=input.toCharArray();

    for (int i = 0; i < vowelArray.length; i++) {
        for(int j=0;j<tmp.length;j++){
            if (vowelArray[i]==tmp[j]){
                input=input.replace(input.substring(j,j+1),(input.substring(j,j+1)+"-"));
                break;
             }   
        }
    }
    return input;
 }

Upvotes: 1

Tega Steve
Tega Steve

Reputation: 11

Instead of using simply a for loop, a foreach loop would do the job then create a string variable to contain and replace the vowel with a vowel plus a dash

Somthing like:

Instead of just a, it becomes a_. Hope it was helpfull

Upvotes: 0

Hihikomori
Hihikomori

Reputation: 990

Try this

if (Character.toString(tmp[i]).matches("[eiuoa]"))

Upvotes: 0

wenzi
wenzi

Reputation: 119

You can use regular expression like this:

String str = "gladiator";  // your input string
str = str.replaceAll("([aeiou])", "$1-");
System.out.println(str);

Upvotes: 2

Related Questions