java 题目、求高手源码
把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到达排序并打印出来。*61.54.231.245*61.54.231.9*61.54.231.246*61...
把以下IP存入一个txt文件,编写程序把这些IP按数值大小,从小到达排序并打印出来。
* 61.54.231.245
* 61.54.231.9
* 61.54.231.246
* 61.54.231.48 61.53.231.249
* 展开
* 61.54.231.245
* 61.54.231.9
* 61.54.231.246
* 61.54.231.48 61.53.231.249
* 展开
1个回答
2013-08-01
展开全部
这里写入操作比较容易,下面是对IP地址排序的解决方案:
class Program
{
static void Main(string[] args)
{
string[] IPS = new string[] { "61.54.231.245", "61.54.231.9", "61.54.231.246", "61.54.231.48", "61.53.231.249" };
Array.Sort<string>(IPS, new Comparison<string>(delegate(string ip1, string ip2)
{
return Comparer<uint>.Default.Compare(ConvertToUInt(ip1), ConvertToUInt(ip2));
}));
for (int i = 0; i < IPS.Length; i++)
{
Console.WriteLine(IPS[i].ToString());
}
Console.ReadKey();
}
private static uint ConvertToUInt(string ip1)
{
string[] sip = ip1.Split('.');
return (uint.Parse(sip[0]) << 24)
| (uint.Parse(sip[1]) << 16)
| (uint.Parse(sip[2]) << 8)
| (uint.Parse(sip[3]));
}
}
class Program
{
static void Main(string[] args)
{
string[] IPS = new string[] { "61.54.231.245", "61.54.231.9", "61.54.231.246", "61.54.231.48", "61.53.231.249" };
Array.Sort<string>(IPS, new Comparison<string>(delegate(string ip1, string ip2)
{
return Comparer<uint>.Default.Compare(ConvertToUInt(ip1), ConvertToUInt(ip2));
}));
for (int i = 0; i < IPS.Length; i++)
{
Console.WriteLine(IPS[i].ToString());
}
Console.ReadKey();
}
private static uint ConvertToUInt(string ip1)
{
string[] sip = ip1.Split('.');
return (uint.Parse(sip[0]) << 24)
| (uint.Parse(sip[1]) << 16)
| (uint.Parse(sip[2]) << 8)
| (uint.Parse(sip[3]));
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询