これは他のいくつかの回答と似ていますが、コードからの変更が行われた理由についていくつかの調整と説明があります。ただし、正規表現がオプションである場合は、Adiの回答をご覧ください。彼は問題に取り組むための別の方法を教えてくれますが、これは宿題なので、それが実行可能な解決策であるかどうかはわかりません. とにかく、説明付き(最終製品の一番下までスキップしてください):
最初に宣言する内容の変更
int vowelCount = 0;
// All the Strings/StringBuilders can be final since we will never reinstantiate them
final String defParagraph = "This is an example sentence.";
// We'll just make a lowercase version here. That way we don't
// .toLowerCase() everytime though the loop, and for people that complain
// about trying to optimize - I think it's easier to read too.
final String lowerCaseVersion = defParagraph.toLowerCase();
// Declare the stringBuilder with the size of defParagraph. That is the
// maximum size the vowel-less text could be, and ensures the stringBuilder
// won't overflow it's initial capacity and have to waste time growing.
final StringBuilder newParagraph = new StringBuilder(defParagraph.length());
// Not using the vowel array. We will remove the loop
// and just || them together - see below
//char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// You didn't need sbParagraph for anything you had (defParagraph works fine).
// Also, you could have just been a regular String since you never changed it.
//StringBuilder sbParagraph = new StringBuilder(defParagraph);
// Don't need vowParagraph since we aren't tracking the actual vowels, just the count
//StringBuilder vowParagraph = new StringBuilder("");
実際のループへの変更
for (int i = 0; i < lowerCaseVersion.length(); i++) {
// grab the current character
char tempChar = lowerCaseVersion.charAt(i);
if ('a' == tempChar || 'e' == tempChar || 'i' == tempChar
|| 'o' == tempChar || 'u' == tempChar) {
// It matched one of the vowels, so count it
vowelCount ++;
} else {
// It didn't match a vowel, so add it the consonants stringBuilder
// Oh, and append a character from the original, not the lowerCaseVersion
newParagraph.append(defParagraph.charAt(i));
}
}
そして、コメントなしですべて一緒に:
int vowelCount = 0;
final String defParagraph = "This is an example sentence.";
final String lowerCaseVersion = defParagraph.toLowerCase();
final StringBuilder newParagraph = new StringBuilder(defParagraph.length());
System.out.println("Characters: " + defParagraph.length());
for (int i = 0; i < lowerCaseVersion.length(); i++) {
char tempChar = lowerCaseVersion.charAt(i);
if ('a' == tempChar || 'e' == tempChar || 'i' == tempChar
|| 'o' == tempChar || 'u' == tempChar) {
vowelCount ++;
} else {
newParagraph.append(defParagraph.charAt(i));
}
}
System.out.println("\tVowel: " + vowelCount);
System.out.println("\tDefPara: " + defParagraph.toString());
System.out.println("\tNewPara: " + newParagraph.toString());
出力は次のようになります。
Characters: 28
Vowels: 9
DefPara: This is an example sentence.
NewPara: Ths s n xmpl sntnc.
ノート
- この場合、使用
final
は本当にオプションです。できる限り使用する傾向がありますが、おそらく個人的な好みです。この質問には、いつ使用するかについての議論final
があり、チェックする価値があるかもしれません。