A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 风雪再现 中级黑马   /  2013-7-5 18:41  /  1980 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

字符串为:"192.168.10.5[port=21,type=ftp]"或者"192.168.10.5[port=21]"提取里面的信息,打印出:ip为:~~,端口号为:~~当存在type时,打印出服务类型:~~,不存在时打印出服务类型为:http

评分

参与人数 1技术分 +1 收起 理由
苏波 + 1

查看全部评分

3 个回复

倒序浏览
            //192.168.10.5[port=21,type=ftp]"或者"192.168.10.5[port=21]"
            //string str = "192.168.10.5[port=21]";//例子
        string str = Console.ReadLine();
            string[] strArrAll = str.Split('[');
            Console.WriteLine("IP为:"+strArrAll[0]);
            if (strArrAll[1].IndexOf(',') >= 0)//说明 存在type
            {
                string[] strArrRight = strArrAll[1].Split(',');
                string port = strArrRight[0].Substring(strArrRight[0].IndexOf('=') + 1);//端口号
          string type = strArrRight[1].Substring(strArrRight[1].IndexOf('=') + 1, strArrRight[1].Length - 1 - strArrRight[1].IndexOf('='));//服务类型
                Console.WriteLine("端口为:"+port);
                Console.WriteLine("服务类型为:"+type);
            }
            else//无type存在
            {
                Console.WriteLine("服务类型为:http");
            }
            Console.Read();

评分

参与人数 1技术分 +1 收起 理由
苏波 + 1

查看全部评分

回复 使用道具 举报
练习手写代码!
先输入!
Console.WriteLine("请输入地址");
//或者直接用192.168.10.5[port=21,type=ftp]
string str=Console.ReadLine();
char[]  remove={'[',']',',','='};
string[] strs=str.Split(remove,StringSpiltOptions.RemoveEmptyEntries);
string IP=strs[0];
string port=strs[2];
string type;
if(strs.Length>3)
type=strs[4];
else
type="http";
Console.WriteLine("ip地址为{0},端口为{1},接口类型为{2}",IP,port,type);
Console.Readkye();

回复 使用道具 举报
static void Main(string[] args)
        {
            string lines = "192.168.10.5[port=21,type=ftp]";     //字符串
            string ip = "";            //IP地址
            string port = "";        //端口
            string type = "http";      //服务类型,默认值为http

            string[] line = lines.Split(new char[] { '[' });      //把字符串按'['分割

            ip = line[0];        //Ip地址为数组中第一个位置的元素

            //再把数组中第二个位置的元素按照','和']'进行分割,形成一个新的字符串数组
            string[] strs = line[1].Split(new char[] { ',', ']' });

            for (int i = 0; i < strs.Length; i++)    //遍历新的字符串数组
            {
                if (strs[i].Contains("port"))           //如果元素里面包含"port"字符串,就提取出里面的端口值
                {
                    port = strs[i].Substring(5);         
                }
                if (strs[i].Contains("type"))         //如果元素里面包含"type"字符串,就提取出里面的服务类型值,否则服务类型就为默认值
                {
                    type = strs[i].Substring(5);
                }

            }

            Console.WriteLine("IP为:" + ip);
            Console.WriteLine("端口为:" + port);
            Console.WriteLine("服务类型为:" + type);

            Console.ReadKey();
        }


回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马