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();

搞定收工~

 

posted @ 2016-09-13 14:49  孟大凡  阅读(5047)  评论(0编辑  收藏  举报