我有一个IP地址:192.168.1.1
。但是我想让它成为192168001001
?我们怎么做?
答案 0 :(得分:3)
易:
var formattedIP = String.Concat("192.168.1.1".Split('.').Select(x => x.PadLeft(3, '0')));
答案 1 :(得分:3)
对我来说,最简洁的方法就是这个:
直接回答:
//String version
string sIP = "192.168.1.1";
string sOut = "";
foreach(string sPart in sIP.Split('.')){
sOut = string.format("{0}{1:000}", sOut, sPart);
}
//IPAddress version
IPAddress oIP = new IPAddress("192.168.1.1");
string sOut = oIP.GetAddressBytes.ToString();
请记住始终使用IPAddress类来解析/检查/操作IP :)。 因为您应该能够使用IPv4和IPv6地址!
http://msdn.microsoft.com/en-us/library/system.net.ipaddress.aspx
答案 2 :(得分:1)
string sIp = "192.168.0.1";
StringBuilder sb = new StringBuilder();
sIp.Split('.').ToList().ForEach(u => sb.Append(u.ToString().PadLeft(3, '0')));
// sb.ToString(); contains the result
答案 3 :(得分:1)
string input = "192.168.1.1";
string[] split = input.Split(new[] { '.' }, StringSplitOptions.None);
string result = string.Join(string.Empty, split.Select(s => s.PadLeft(3, '0')));
答案 4 :(得分:1)
string str1 = "192.168.1.1";
string[] str = str1.Split('.');
for(int i = 0; i < str.Length; i++)
str[i] = int.Parse(str[i]).ToString("000");
str1 = string.Join("", str);
现在str1
包含"192168001001"
答案 5 :(得分:1)
这样做:
string ip = "192.168.12.1";
StringBuilder stringBuilder = new StringBuilder();
string[] array = ip.Split('.');
foreach (string subsection in array)
{
if (subsection.Length < 2)
stringBuilder.Append("00" + subsection);
else if (subsection.Length < 3)
stringBuilder.Append("0" + subsection);
else
stringBuilder.Append(subsection);
}
答案 6 :(得分:0)
试试这个
string FormatIP(string ip)
{
string[] data = ip.Split('.');
if (data.Length > 4)
throw new Exception("Invalid IP address");
List<string> finalIP = new List<string>();
int intChunk;
string temp;
foreach (string chunk in data)
{
temp = chunk;
if (temp.Length > 3 || int.TryParse(temp, out intChunk) == false || intChunk > 255)
throw new Exception("Invalid IP address");
while (temp.Length < 3)
temp = "0" + temp;
finalIP.Add(temp);
}
data = finalIP.ToArray();
return string.Join(".", data);
}