public class IPSort {
public static void main(String[] args) {
// IP 排序
// 10.2.9.48, 192.168.1.2, 202.155.10.2, 173.68.46.65
String[] ips = {
"19.2.9.48", "192.168.1.2", "202.155.10.2", "173.68.46.65"
};
//------------------------------------------------------------------
//Arrays.sort排序,根据字符排序,所以必须是同样的位数。否则如下例子
/*Arrays.sort( ips ); //做排序 ...
for( int i=0; i<ips.length; i++ ){
System.out.println( ips[i] );
}*/
//结果为:173.68.46.65 , 19.2.9.48 , 192.168.1.2 , 202.155.10.2
//------------------------------------------------------------------
for( int i=0; i<ips.length; i++ ){
//补零操作, 为什么要补两个零, 考虑的位数是 1 位, 所以要被两个零
ips[i] = ips[i].replaceAll( "(\\d+)", "00$1" );
//System.out.println( ips[i] );
//截成三个位, 限定后面的一定要有三位数, 前面我不管(会被截断)
ips[i] = ips[i].replaceAll( "0*(\\d{3})", "$1" );
//System.out.println( ips[i] );
}
Arrays.sort( ips ); //做排序 ...
for( int i=0; i<ips.length; i++ ){
System.out.println( ips[i] );
}
//去零处理 ...
for( int i=0; i<ips.length; i++ ){
ips[i] = ips[i].replaceAll( "0*(\\d+)", "$1" );
System.out.println( ips[i] );
}
}
}
java ip排序实例
最新推荐文章于 2023-08-31 16:12:42 发布