2つの文字列間で一致しない文字の数を見つける必要があります。現在、文字列をchar配列に変換し、要素ごとに比較することでこれを行っています。
上記の要件を達成する他の方法はありますか?
注:文字列は小文字と見なして
入力:
入力
utput
出力:
2
StringUtils
in Apache commons.lang には、2 つの文字列のレーベンシュタイン距離を取得するメソッドがあります。
これはあなたが説明している方法ですが、実装する最も簡単な方法です:
int counter = 0;
for(int i = 0; i < str1.length(); i++) if(str1.charAt(i) != str2.charAt(i)) counter++;
それらは、まったく新しい文字配列を明示的に作成しなくても、わずか 2 行のコードに収まります。
2 つの文字列のサイズが異なる場合、次のコードはアルファベットの完全な不一致を返します。
あなたはこれを試すことができます -
String ip1 = "input"; // input1
String ip2 = "utput"; // input2
int count = 0; // difference in string
String ipx2 = ip2;
for (int j = 0; j <= ip2.length(); j++) {
int value = ip1.indexOf(ipx2);
if (value != -1) {
if (("").equals(ipx2)) { // if the second string is blank after continous reducing
count = ip1.length() + ip2.length();
} else {
count = ip1.length() + ip2.length() - 2 * ipx2.length();
}
break;
} else {
count = ip1.length() + ip2.length(); // if there is no match at all
}
ipx2 = ip2.substring(j);
}
System.out.println("" + count);
}
入力にデータがあるかどうかを確認する必要があります。そのチェックはしていません。