我需要将字符串值分别拆分为不同的变量

I need to get the string value split in different variables individualy

我想单独从字符串中获取值并将其存储在变量中,以便我可以检查它们是否有效。

Int32 count = 1;
string ip = ("198.170.60.90");
char[] separator = { '.' };
string[] address = ip.Split(separator,count,StringSplitOptions.RemoveEmptyEntries);
foreach(string x in address)
{
    Console.WriteLine(x);
}

我正在尝试编写一个程序来检查 IP 地址的有效性,我的导师告诉我搜索 String.Split 方法。

比你做的简单多了。

请检查这段代码:

string ip = "198.170.60.90";
var splittedString = ip.Split('.');
foreach(var element in splittedString){
  Console.WriteLine(element);
}

它产生这个输出:

198  
170  
60  
90

你在方法调用中使用的参数,准确地说是count = 1 ,意味着你希望字符串将被拆分成正好 1个元素——所以它会不被分裂。 如果您想继续使用它,只需将计数值增加到您期望的拆分元素数即可。

也许您尝试检查 IP 是否有效?

System.Net.IPAddress _ip = null;    
bool isValidIp = System.Net.IPAddress.TryParse("192.168.1.33", out _ip);

你的方向是对的:

  1. 拆分字符串。
  2. 确保获得预期数量的零件。
  3. 迭代各个部分以单独检查它们。

在代码中,这将是:

private bool IsValid(string ipAddress)
{
    // Split the string parts by the character '.'.
    string[] ipAddressParts = ipAddress.Split('.', StringSplitOptions.RemoveEmptyEntries);

    // Make sure the ip address has four parts
    if (ipAddressParts.Length != 4)
    {            
        return false; 
    }
    
    // Iterate the ip address parts to check them individually
    foreach (string part in ipAddressParts)
    {
        // Make sure the part is an integer
        if (int.TryParse(part, out int numericPart))
        {
            // Make sure the integer part is between 0-255
            if (numericPart < 0 || numericPart > 255)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    return true;
}

使用示例:

bool isValid = IsValid("198.170.60.90"); // true

bool isValid = IsValid("198...60.90"); // false

bool isValid = IsValid("198.170.5a.90"); // false

看来您最好使用 System.Net 中的 IPAddress class:

string ip = "192.170.60.90";
if (IPAddress.TryParse(ip, out var ipAddress)) // parse the ip
{
    foreach (byte b in ipAddress.GetAddressBytes()) // go through each octet
    {
        Console.WriteLine(b); // write the octet
    }
}
else
{
    Console.WriteLine("IP not valid.");
}

输出:

192
170
60
90

Try it online

文档: