Bluasul
Bluasul

Reputation: 325

Incorrect output in small program. Why is this String variable not doing what I want it to?

This program should take a String, check if each letter is a vowel and change the vowels into underscores. For example, if I enter some it should output s_m_. This is a simple programming exercise that I feel like I should be able to do. However I am genuinely stumped and can't tell what I'm doing wrong.

I have declared an array to keep the vowels, a newStr variable which will contain the updated string ,and I'm looping through the string, comparing each letter using charAt() to check if it's in the vowels array. If it is, I add _ to the updated String, and I keep the original letter if it's not. The final output is wrong, what am I doing wrong?

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

for (int x = 0; x < str.length(); x++) {
    char letter = str.charAt(x);

    for (int j = 0; j < vowels.length; j++) {
        if (letter == vowels[j]) {
            newStr = newStr + '_';
            break;
        } else {
            newStr = newStr + letter;
            break;
        }
    }
}

out.println(newStr);

Upvotes: 0

Views: 116

Answers (3)

Minn
Minn

Reputation: 6134

In your code the issue is within your nested "for-loop". I say this in quotes because it never actually loops. The first iteration j=0 immediately breaks the loop since either your letter is equal to a with (letter == vowels[0]) or not. In either case you do a break; and append the character. This means your loop can be reduced to a simple if-else that checks if the letter is an a and replaces it with _ or keeps it.

To fix this issue you need to use a different approach. You can create a String of vowels such as "aeiouAEIOU" and use indexOf to test whether the selected character is a vowel.

public static String omitVowels(String input) {
    StringBuilder out = new StringBuilder(input.length());
    String vowels = "aeiouAEIOU";
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (vowels.indexOf(c) >= 0) // is vowel if index not negative
            out.append('_');
        else
            out.append(c);
    }
    return out.toString();
}

indexOf(char) will return -1 if the provided character is not part of the string, else it will return the specific index. We can use this property to test whether the character is a vowel or not.

Examples

omitVowels("hello world") -> "h_ll_ w_rld"

omitVowels("aeiou") -> "_____"

omitVowels("TESTing") -> "T_ST_ng"

Upvotes: 2

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

This is pretty simple. Just iterate over each character of the given string and replace with _ in case of it is vowel.

Use StringBuilder

Be ware of using String. This is immutable in java, therefore to build final string, you should use StringBuilder.

public static String replaceVowel(String str) {
    final IntPredicate isVowel = ch -> ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
    StringBuilder buf = new StringBuilder(str.length());

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        boolean vowel = isVowel.test(Character.toLowerCase(ch));
        buf.append(vowel ? '_' : ch);
    }

    return buf.toString();
}

Use RegularExpression

As alternative, you can use Regular Expression with replaceAll() method of the String class.

private static final Pattern VOWEL = Pattern.compile("[aeiou]");

public static String replaceVowel(String str) {
    return VOWEL.matcher(str).replaceAll("_");
}

This is also correct, because in the background, replaceAll() uses StringBUilder.

Upvotes: 0

Naya
Naya

Reputation: 870

for (int x = 0; x < str.length(); x++) {
 char letter = str.charAt(x);
 boolean toReplace = false;
 for (int j = 0; j < vowels.length; j++) {
    if (letter == vowels[j]) {
        toReplace = true;
        break;
    }
 }
 if (toReplace) {
    newStr = newStr + "_";
 } else {
    newStr = newStr + letter;
 }
}

Upvotes: -1

Related Questions