String.split() 测试
1、去掉所有 \r \n :
1 public static void main(String[] args) 2 { 3 String str = "A\r\nB\nc"; 4 String[] strs = str.split("[\r\n]+"); 5 for (int i=0; i<strs.length; i++) 6 System.out.println(strs[i]); 7 8 System.out.println(""); 9 10 str = "Ac\r\r\nB1\n\nc2"; 11 strs = str.split("[\r\n]+"); 12 for (int i=0; i<strs.length; i++) 13 System.out.println(strs[i]); 14 }
输出为:
1 A 2 B 3 c 4 5 Ac 6 B1 7 c2
2、
代码:
1 public static void main(String[] args) 2 { 3 String str = "a c v f b t "; 4 String[] strs = str.trim().split(" +", 3); 5 System.out.println("strs.length(1) : "+strs.length); 6 for (int i=0; i<strs.length; i++) 7 System.out.println(strs[i]); 8 9 System.out.println(""); 10 str = "a cccccc"; 11 strs = str.trim().split(" +", 3); 12 System.out.println("strs.length(2) : "+strs.length); 13 for (int i=0; i<strs.length; i++) 14 System.out.println(strs[i]); 15 }
输出:
strs.length(1) : 3 a c v f b t strs.length(2) : 2 a cccccc
C