は、他の2つの答えは、右の出力を生成しますが、彼らは非常に効率的ではないので、ここで私のテイクがあります。
consonants
は定数である必要があります。単純に小文字で指定する必要があります。定数として、大文字(CONSONANTS
)で名前を付ける必要があります。
文字を置換するには、toCharArray()
を使用して元の文字列のchar[]
を取得し、配列を変更してnew String(char[])
を使用して新しい文字列を作成します。
CONSONANTS
の文字のインデックスを見つける最も簡単な方法は、indexOf()
メソッドを使用することです。
インデックスに1を加算するときのオーバーフローを防ぐには、係数演算子(%
)を使用します。
private static final String CONSONANTS = "bcdfghjklmnpqrstvwxyz";
private static String shiftConsonants(String input) {
char[] chars = input.toLowerCase().toCharArray();
for (int i = 0; i < chars.length; i++) {
int idx = CONSONANTS.indexOf(chars[i]);
if (idx != -1)
chars[i] = CONSONANTS.charAt((idx + 1) % CONSONANTS.length());
}
return new String(chars);
}
試験:ここ
System.out.println(shiftConsonants("Java")); // prints: kawa
は、元のケースを保持する代替の解決策です。
private static final String CONSONANTS = "bcdfghjklmnpqrstvwxyz";
private static String shiftConsonants(String input) {
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i++) {
char ch = chars[i];
char lower = Character.toLowerCase(ch);
int idx = CONSONANTS.indexOf(lower);
if (idx != -1) {
char next = CONSONANTS.charAt((idx + 1) % CONSONANTS.length());
chars[i] = (ch == lower ? next : Character.toUpperCase(next));
}
}
return new String(chars);
}
テスト:
System.out.println(shiftConsonants("Java")); // prints: Kawa
フォローアップcomment by @MistahFigginsへ:
なり、各文字のためにint型にキャストして、番号を変更しても、バックキャスティング多かれ少なかれ効率的ですか?
私の推測は間違っていました。小文字のバージョン(上記の最初のバージョン)では、数値の増分は36%です。
private static String shiftConsonants(String input) {
char[] chars = input.toLowerCase().toCharArray();
for (int i = 0; i < chars.length; i++) {
char ch = chars[i];
if (ch == 'z')
chars[i] = 'b';
else if (ch >= 'b' && ch <= 'y' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
ch = (char)(ch + 1);
if (ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
ch++;
chars[i] = ch;
}
}
return new String(chars);
}
ご覧のとおり、a
も考慮しないように最適化されています。
FYI: "*アルファベット*" は、例えば、適切な言語/国で* *手紙の全配列であります英語のA-Z。したがって、「子音を次のアルファベットに置き換える」は、「子音を次の文字に置き換える」、またはより具体的には、「アルファベットの子音を次の子音に置き換える」必要があります。 – Andreas