字符串方法-IP解析

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 字符串方法-IP解析
{
    class Program
    {
        #region 练习6
        //static void Main(string[] args)
        //{
        //    Console.WriteLine("请输入文件名");
        //    string line = Console.ReadLine();

        //    string name = MyPath.GetDirectory(line);
        //    Console.WriteLine(name);
        //    Console.ReadKey();
        //} 
        #endregion



        static void Main(string[] args)
        {
            // 练习7:“192.168.10.5[port=21,type=ftp]”,这个字符串表示
            // IP地址为192.168.10.5的服务器的21端口提供的是ftp服务,其
            // 中如果“,type=ftp”部分被省略,则默认为http服务。请用程序解
            // 析此字符串,然后打印出“IP地址为***的服务器的***端口提供的
            // 服务为***” line.Contains(“type=”)。192.168.10.5[port=21]

            string s1 = "192.168.10.5[port=21,type=ftp]";
            string s2 = "192.168.10.5[port=21]";

            string s3 = "202.123.234.111[port=34567,database=127.0.0.1,domain=www.jk.jk.jk]";

            // 首先是IP
            string[] temps = s3.Split("[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            // [0]  IP
            // [1]  键值对

            string ip = temps[0];
            
            // 
            string[] subTemps = temps[1].Split(',');
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < subTemps.Length; i++)
            {
                // 获得端口号与服务类型
                string[] ss = subTemps[i].Split('=');
                // [0]  名字
                // [1]  值
                dic.Add(ss[0], ss[1]);
            }
            // 是否存在type,如果存在就表示有提供,否则表示默认的http,需要手动提供
            if (!dic.ContainsKey("type"))
            {
                dic.Add("type", "http");
            }

            // 打印出结果
            Console.WriteLine("IP:" + ip);
            foreach (KeyValuePair<string, string> item in dic)
            {
                Console.WriteLine("{0}:{1}", item.Key, item.Value);
            }
            Console.ReadKey();
        }
    }
}
原文地址:https://www.cnblogs.com/blacop/p/6013003.html