import java.util.Arrays;
public class IPAddressSort {
public static void main(String[] args) {
String[] ip = { "255.2.3.4", "172.7.8.2", "192.10.8.9", "192.10.8.7", "2.3.4.5", "2.4.5.6", "1.2.3.45" };
ip = fill(ip); //先填充ip地址,前面补0
Arrays.sort(ip); //调用Arrays里的sort(Object[] o)方法进行排序
ip = recovery(ip); //回复ip地址,去除补上的0
for (String s : ip) { //输出效果
System.out.println(s);
}
}
static String[] fill(String[] ip) {
for (int i = 0; i < ip.length; i++) {
String[] temp = ip[i].split("\\."); //字符串分组split()方法里是填正则表达式。所用用“\\.”
ip[i] = ""; //先设为空字符
for (int j = 0; j < temp.length; j++) {
if (Integer.parseInt(temp[j]) / 10 == 0) { //当该ip段为0-9时,前面补两个0
temp[j] = "00" + temp[j];
} else if (Integer.parseInt(temp[j]) / 100 == 0) { //当该ip段为10-99时,前面补一个0
temp[j] = "0" + temp[j];
}
ip[i] += temp[j] + "."; //重新赋值
}
ip[i] = ip[i].substring(0, ip[i].length() - 1); //去除最后一个多余的“.”
}
return ip;
}
static String[] recovery(String[] ip) {
for (int i = 0; i < ip.length; i++) {
String[] temp = ip[i].split("\\.");
ip[i] = "";
for (int j = 0; j < temp.length; j++) {
if (temp[j].startsWith("00")) { //去除0-9前面的0,一定要放前面
temp[j] = temp[j].substring(2);
} else if (temp[j].startsWith("0")) { //去除10-99前面的0,一定要放后面
temp[j] = temp[j].substring(1);
}
ip[i] += temp[j] + ".";
}
ip[i] = ip[i].substring(0, ip[i].length() - 1);
}
return ip;
}
}
//用2L的思路实现的。这个思路比较好。
追问--分就给你吧,同时也感谢AiDirac--想得周全;只是所有答案都太繁琐了,我用Ruby解决了,代码如下:
ip_array = []
IO.foreach("ip.txt") { |line|
line.chomp
ip_array << line.split(/\./).map!{ |o| o.to_i }.pack("C*")
}
ip_array.sort.each { |ip|
print ip.unpack("C*").join("."), "\n"
}
本回答被提问者采纳