java使用split切割字符串的時候,注意轉義字符


今天在做項目的時候發現一個奇怪的問題

 1 File file = new File("d:\\a.txt");
 2         BufferedReader br = new BufferedReader(new FileReader(file));
 3 
 4         String text = "";
 5         while ((text = br.readLine()) != null) {
 6 
 7             String[] s = text.split("|");
 8             for (int i = 0; i < s.length; i++) {
 9                 System.out.print("切割字符串" + s[i] + "\t");
10             }
11             System.out.println();
12         }
13         br.close();

運行的結果

發現每一個字符都給我切割了,后來在網上查到,當以  |  切割的時候一定要注意使用轉義字符

 1 File file = new File("d:\\a.txt");
 2         BufferedReader br = new BufferedReader(new FileReader(file));
 3 
 4         String text = "";
 5         while ((text = br.readLine()) != null) {
 6 
 7             String[] s = text.split("\\|");
 8             for (int i = 0; i < s.length; i++) {
 9                 System.out.print("切割字符串" + s[i] + "\t");
10             }
11             System.out.println();
12         }
13         br.close();

搞定收工~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM