java new line replacement

前端 未结 2 731
半阙折子戏
半阙折子戏 2021-01-13 09:42

I am wondering about why I don\'t get the expected result with this one:

String t = \"1302248663033   

        
2条回答
  •  孤街浪徒
    2021-01-13 10:13

    Yes, \n is special. It is an escape sequence that stands for a newline. You need to escape it in a string literal in order for it to be actually interpreted the way you want. Append a \ before the sequence so that it looks like this:

    "\\n"
    

    Now your program should look like this:

    String t = "1302248663033   ";
    t = t.replaceAll("\\n", "");
    System.out.println(t);
    

    Of course if the string t is coming from somewhere rather than actually being typed by you into the program then you need only add the extra slash in your call to replaceAll()

    Edited according to comments.

提交回复
热议问题