I've written a code which is intended to insert string "av"
before any vowel in the given String
, which is not be preceded by another vowel.
Consider the String
as an input:
"aadeleo"
After adding "av"
before each and every vowel which are not preceded by another vowel, the output should be:
"avaadavelaveo"
But my code produces:
"avaavadavelaveavo"
My code:
public class Main {
public static void main(String[] args) {
String st = "aadeleo";
String word = "";
int l = st.length();
char c, c2;
for (int i = l - 1; i > 0; i--) {
c = st.charAt(i);
c2 = st.charAt(i - 1);
if ((c == 'a' || c == 'e' ||
c == 'i' || c == 'o' ||
c == 'u') && (c2 != 'a' || c2 != 'e' ||
c2 != 'i' || c2 != 'o' ||
c2 != 'u')) {
word = "av" c word;
} else
word = c word;
}
c = st.charAt(0);
if (c == 'a' || c == 'e' ||
c == 'i' || c == 'o' ||
c == 'u')
word = "av" c word;
else
word = c word;
System.out.println(word);
}
}
CodePudding user response:
There's no need to double-check the previous character since it has already been seen.
The logic for determining whether a character is a vowel can be extracted into a separate method, that would make the code more readable. To perform this check, we can use String.indexOf(char)
method instead of a swarm of conditions.
And it's highly advisable to avoid string-concatenation when you're not sure how many times it might take place. The better option would be to use StringBuidler
.
That's how it might be implemented:
public static String insertBeforeNonPrecededVowel(String str, String insert) {
StringBuilder result = new StringBuilder();
boolean isPrecededByVowel = false;
for (int i = 0; i < str.length(); i ) {
char next = str.charAt(i);
boolean nextIsVowel = isVowel(next);
if (nextIsVowel && !isPrecededByVowel) result.append(insert); // if current character is Vowel, and it's not preceded by Vowel
isPrecededByVowel = nextIsVowel;
result.append(next);
}
return result.toString();
}
public static boolean isVowel(char ch) {
return "aeiou".indexOf(ch) != -1;
}
main()
public static void main(String[] args) {
System.out.println(insertBeforeNonPrecededVowel("aadeleo", "av"));
}
Output:
avaadavelaveo