String.replaceAll("","");
Java の文字列から「空白」または「印刷されない文字」を排除する手段としての使用への参照を見てきました。答えが示すように、これは誤りです。
value = value.replaceAll("", "");
Junit を使用して、\u0000 から \uffff までのすべての Unicode 文字をテストします。
@Test
public void testReplaceBlanks(){
char input = 0;
char escape = '\u0000';
for(char i = 0; i <= 65535; ++i){
input = (char) (escape + i);
System.out.print(input);
System.out.print(" ");
if( i % 80 == 0){
System.out.println();
}
String test = new String(Character.toString(input));
assertTrue(!"".equals(test.replaceAll("", "")));
if(i == 65535)
break;
}
}
そのコード行が何か有用なことをする単一のインスタンスが見つかりません。
この問題をインターネットでさらに数回発見したので、より堅牢なテストケースを次に示します。
ここでの大きな問題です。このコード行は NO-OP です。
value = value.replaceAll(“”, “”);
次のテスト ケースを検討してください。
public static void println(String s) {
System.out.println(s);
}
@Test
public void testNullStripWithEmptyString() {
String input = "foo" + '\0';
String input2 = "foo";
println(input);
println("input:");
printBytes(input.getBytes());
println("input2:");
printBytes(input2.getBytes());
String testValue = input.replaceAll("", "");
println("testValue:");
printBytes(testValue.getBytes());
String testvalue2 = input2.replaceAll("","");
println("testvalue2");
printBytes(testvalue2.getBytes());
assertFalse(input.equals(input2));
assertFalse(testValue.equals(testvalue2));
}
このテスト ケースは、最初に、2 つの入力文字列のバイト表現で、null バイトが最初に表示され、2 番目には表示されないことを示しています。次に、*.replaceAll(“”,””); の呼び出しに進みます。値を 2 つの新しい変数 testValue と testvalue2 に格納します。
これは、通常の String equals メソッドを呼び出して、2 つの値が等しくないことをアサートする最初のアサートにつながります。文字列に付加された印刷されないヌル バイトがあるため、これは当然のことです。ただし、棺桶の釘は、 *.replaceAll(“”,””); を呼び出した後もこの状態が引き続き保持されることを示しています。2 つの testValue 文字列について。
非印刷または NULL バイトを防ぐ唯一の方法は、次のテスト ケースを実装することです。
@Test
public void testNullStripWithNullUnicodeEscape(){
String input = "foo" + '\0';
String input2 = "foo";
println(input);
println("input:");
printBytes(input.getBytes());
println("input2:");
printBytes(input2.getBytes());
String testValue = input.replaceAll("\u0000", "");
println("testValue:");
printBytes(testValue.getBytes());
String testvalue2 = input2.replaceAll("\u0000","");
println("testvalue2");
printBytes(testvalue2.getBytes());
assertFalse(input.equals(input2));
assertTrue(testValue.equals(testvalue2));
}