How to insert a syllable before a single vowel

Viewed 261

I try to insert a syllable before each vowel with the following restrictions:

- Before each following vowel (a, e, i, o, u), insert the stray syllable "av".

- Unless the vowel is preceded by another vowel

Actually I've done this

public static String translate(String text) {
    char [] charArray = text.toCharArray();
    StringBuilder sb = new StringBuilder();

    for(char c : charArray) {
        if (charArray.length < 255){
            if (isVowel(c)) {
                sb.append(String.format("av%s" , c));
            }
            else {
                sb.append(c);
            }
        }
    }
    return sb.toString();
}

static boolean isVowel(char c) {
    return (c == 'a') || (c == 'e') ||
            (c == 'i') || (c == 'o') ||
            (c == 'u');
}

With words without double vowels it works perfectly:

Cat becomes

Cavat

But with double vowel it doesn't work

Meet becomes

Maveavet // Should return Meet

How to check if 2 successive letters are vowels in order not to add the syllable if it's the case ?

Thanks in advance

2 Answers

Here is a version that uses an ordinary for loop:

public static String translate(String text) {
    char [] charArray = text.toCharArray();
    StringBuilder sb = new StringBuilder();

    Set<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u'));

    char cFirst = charArray[0];
    if (vowels.contains(cFirst) && !(vowels.contains(charArray[1]))) {
        sb.append(String.format("av%s" , cFirst));
    }
    else sb.append(cFirst);

    for (int i = 1; i < charArray.length-1; i++){
        char c = charArray[i];
        char cNext = charArray[i+1];
        char cPrev = charArray[i-1];

        if (vowels.contains(c) && !(vowels.contains(cNext) || vowels.contains(cPrev))) {
            sb.append(String.format("av%s" , c));
        }
        else sb.append(c);
    }

    char cLast = charArray[charArray.length-1];
    if (vowels.contains(cLast) && !(vowels.contains(charArray[charArray.length-2]))) {
        sb.append(String.format("av%s" , cLast));
    }
    else sb.append(cLast);

    return sb.toString();
}

Works for all the cases I could think of, but probably not the optimal way of doing this.

One approach is to manage the indexes yourself instead of using an enhanced for loop. This allows you to 'skip' over two vowel chunks by checking the next character if it exists. Something like this should work:

    int i = 0;
    while (i < charArray.length) {
        char c = charArray[i];
        if (isVowel(c)) {
            if (i + i == charArray.length || isVowel(charArray[i+1])) {
                sb.append("av");
            } else {
                i++;
            }
        }
        sb.append(c);
        i++;
    }

Note that this does not solve for when there are three sequential vowels.

Related