0

\すべてを置き換えようとして%5Cいますが、間違った出力が得られます:

String str="a\b";
str=str.replaceAll("\\\\", "%5C");
System.out.println(str);
4

3 に答える 3

8

変数strにバックスラッシュが含まれていません。何らかの方法で引数のバックスラッシュを正しくエスケープしましたreplaceAll()が、への元の割り当てではエスケープしませんでしたstr

String str="a\b";

なる必要があります:

String str="a\\b";
于 2012-10-26T11:02:54.273 に答える
3

replaceAll結果を返すので、結果を変数に割り当ててみてください。

        // TODO Auto-generated method stub
        String str="a\b";
        str = str.replaceAll("\\\\", "%5C");
        System.out.println(str);
于 2012-10-26T11:03:29.077 に答える
1

strあなたによると正しくないので、最初にあなたはあなたを変えなければならないと思います。
次のコードを使用します。

    // TODO Auto-generated method stub
    String str="a\\b";
    str=str.replaceAll("\\\\", "%5C");
    System.out.println(str);

コードが機能しないのは

A character preceded by a backslash (\) is an escape sequence and has special 
meaning to the compiler. The following table shows the Java escape sequences.

つまり、a\bにはエスケープシーケンス\bという特別な意味があります。 それが機能しない理由ですので、キャラクターをエスケープする必要があります。Insert a backspace in the text at this point.
\

于 2012-10-26T11:08:07.593 に答える