C#输入IP地址并检查格式再进行分截取

using System;

namespace CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            bool shutdown = true;
            while (shutdown)
            {
                Console.Write("\n请输入一个IP地址:");
                string ipAddr = Console.ReadLine();
                if (ipAddr.Length >= 7 && ipAddr.Length <= 15)
                {
                    string[] splitIP = new string[4];
                    for (int i = 0; i < 3; i++)
                    {
                        splitIP = ipAddr.Split('.');
                    }

                    bool flag = true;
                    for (int i = 0; i < splitIP.Length; i++)
                    {
                        if (int.Parse(splitIP[i]) < 0 || int.Parse(splitIP[i]) > 255)
                        {
                            Console.WriteLine("提示:IP格式有误!");
                            flag = false;
                            continue;
                        }
                        if (flag)
                        {
                            Console.Write(splitIP[i] + "\t");
                            shutdown = false;
                        }
                    }
                    Console.WriteLine();
                    break;
                }
                else
                {
                    Console.WriteLine("提示:IP格式有误!");
                    continue;
                }
            }
            
            Console.ReadLine();
        }
    }
}

运行示范:
在这里插入图片描述

你可能感兴趣的:(典化成籍-C#,C#,Substring,IP格式,Split)