Array和String测试与java.String.split

java.string.split()

存在于java.lang包中,返回值是一个数组。
作用是按指定字符或者正则去切割某个字符串,结果以字符串数组形式返回。

 String [] toSort =
 //  0   1 2 3
  {"aaa:10:1:1",    
   "ccc:30:3:4",           
   "bbb:50:4:5",
   "ddd:20:5:3",        
   "eee:40:2:20"};

经过toSort[i].split(":")切割会返回每一列字符串数组。

通过选取列数决定比较规则。


 import java.util.*;

 public class MySort1 {
     public static void main(String [] args) {
         String [] toSort = {"aaa:10:1:1",
                             "ccc:30:3:4",
                             "bbb:50:4:5",
                             "ddd:20:5:3",
                             "eee:40:2:20"};

         System.out.println("Before sort:");
         for (String str: toSort)
                  System.out.println(str);

         Arrays.sort(toSort);
    
         System.out.println("After sort:");
         for( String str : toSort)
             System.out.println(str);
         
         
         System.out.println("After toSort:");
         int  [] tmp = new int [toSort.length];
         String [][] tmpp = new String[toSort.length][4];
        for (int i = 0; i< toSort.length; i++){
        	  tmpp[i] = toSort[i].split(":");
        	  tmp[i] = Integer.parseInt(tmpp[i][2]);// 控制选取的列
        	  
        	  }
        
        
        
        Arrays.sort(tmp);
        for (int i = 0; i < tmp.length; i++) {
            for (int j = 0; j < toSort.length; j++) {
                if(tmp[i] == Integer.parseInt(tmpp[j][2])){
                //与排过序的数组tmp进行比较
                    System.out.println(toSort[j]);
                }
            }
        }
      
        
}
 }

特别的,一些正则字符做间隔需要转译后才能使用,如 | + * ^ $ / | [ ] ( ) - .

String str = "1234|56";
String[] a = str.split("\|"); 
System.out.println("处理结果: "+a[0]+","+a[1]);   //输出的是: 处理结果: 1234,56

用split方法测试String类

测试

在IDEA中以TDD的方式对String类和Arrays类进行学习

码云链接

原文地址:https://www.cnblogs.com/ikari/p/6852876.html