I was wondering if I could get some help on a proper way of appending consonants to a StringBuilder variable.
As it stands right now, it successfully finds and counts up the number of vowels found in a sentence, however, I’m having trouble creating a new variable that excludes them.
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
int vowelCount = 0;
String defParagraph = "This is an example sentence.";
StringBuilder sbParagraph = new StringBuilder(defParagraph);
StringBuilder vowParagraph = new StringBuilder("");
System.out.print("Characters: " + sbParagraph.length());
for (int i = 0; i < sbParagraph.length(); i++) {
for (int j = 0; j < vowels.length; j++) {
if (sbParagraph.toString().toLowerCase().charAt(i) == vowels[j]) {
vowelCount++;
}
}
}
I’ve tried simply adding a vowParagraph.append(sbParagraph.charAt(i) in the loop, but it gives me multiples of the same character in the new string. I’ve also given thought to copying the original StringBuilder variable and simply removing the characters but I simply don’t know the best way to go about doing that.
I’m not sure if I should stick with two loops and an array, or if I should simply make a massive if/then condition to check for values. To be honest that seems like the easiest way, but also seems a bit too verbose and inefficient.
If anyone can help me shed light on my foolishness I’d appreciate it. This has been driving me nuts.
You can change your loop like this to avoid multiples: