在java中除去字符串(String)中的換行字符(\r \n \t)

 

我們先來看幾個例子:

例1:

public class Test {

 public static void main(String[] args) {


  String s = "'sds gdasda" + "\n" + "edaeafd'";
  System.out.println("轉換前:"+s);


  s = s.replaceAll("\r|\n", "");


  System.out.println("轉換後:"+s);
  }
}
 輸出結果:

轉換前:'sds gdasda
edaeafd'
轉換後:'sds gdasdaedaeafd'

在看一個實例:

例2:

System.out.println("\\r 輸出:"+"abc"+"\r"+"abc");
  System.out.println("\\n輸出:"+"abc"+"\n"+"abc");

以上兩句在控制檯輸出的格式是一樣的:

\r輸出:abc
abc
\r輸出:abc
abc

 

那麼是不是說\r與\n是不是相等的呢?

例3:

public class Test {

 public static void main(String[] args) {


  String s = "'sds gdasda" + "\n" + "edaeafd'";
  System.out.println("轉換前:"+s);


  s = s.replaceAll("\r", "");


  System.out.println("轉換後:"+s);
  }
}

轉換前:'sds gdasda
edaeafd'
轉換後:'sds gdasda
edaeafd'

輸出結果可以看出\r和\n啊hi不相等的。

 

 

那麼他們有什麼區別呢?

例4:

public class Test {

 public static void main(String[] args) {


  String s = "'sds gdasda" + "\n\r" + "edaeafd'";

  System.out.println("轉換前:"+s);


  s = s.replaceAll("\r|\n", "");


  System.out.println("轉換後:"+s);
  }
}

輸出結果:

轉換前:'sds gdasda

 

edaeafd'
轉換後:'sds gdasdaedaeafd'

可以看出\r表示回車,\n表示另起一行(\r 叫回車 Carriage Return  ;\n 叫新行 New Line

我們可以在所一個實驗:

例5:

public class Test {

 public static void main(String[] args) {


String s = "'sds gdasda" + "\r\n" + "edaeafd'";

  System.out.println("轉換前:"+s);


  s = s.replaceAll("\r|\n", "");


  System.out.println("轉換後:"+s);
  }
}

 

輸出結果:

轉換前:'sds gdasda
edaeafd'
轉換後:'sds gdasdaedaeafd'

例4到例5中我們只是把字符串s的\n\r的位置改變成了\r\n,卻發現例4輸出結果中多了一行空格。

至於爲什麼例4和例5輸出會有這樣的區別也就是\r\n與\n\r的區別,這是網上的一個比較好的答案:

enter+newline with different platforms:
windows:   \r\n
mac:           \r
unix/linux:  \n

 
in "abc" + ”\n\rdef”, \n\r   do not match any platform,so it is considered as \n and \r  (which match unix/linux  and mac),so there are two new lines.
in  "abc" + ”\r\ndef”   \r\n matches the windows platform,so it is considered as only one new line.
scim crushed, so just English.
 

 關於\t 它相當於按了一下Tab鍵

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章