今天在做项目的时候发现一个奇怪的问题

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

运行的结果
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();

搞定收工~

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
  • 2021-11-05
  • 2021-11-14
猜你喜欢
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案