一道C#字符串的题目

如题:

给定一个字符串,比如yycc12long34567yc,通过写一个小程序,将字符串中最长的数字取出来。

一开始我想到的是,遍历这个字符串每个字符,再根据是否数字拼接新的字符串,并存储到新的对象中

代码如下:

       /// <summary>
        /// 方法一
     /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn1_Click(object sender, EventArgs e)
        {
            string str = tbStr.Text;
            int l = str.Length;
            char[] chars = str.ToCharArray();
            List<string> strTemp = new List<string>();

            string sTemp = string.Empty;
            int n = 0;
            //遍历每个字符
            foreach (char c in chars)
            {
                //是数字则累加
                if (int.TryParse(c.ToString(), out n))
                {
                    sTemp += c.ToString();
                }
                else
                {
                    //否则将上次结果加到list,并置空
                    if (int.TryParse(sTemp, out n))
                    {
                        strTemp.Add(sTemp);
                        sTemp = string.Empty;
                    }
                }
            }

            //最后一次结果是数字的加到list
            if (int.TryParse(sTemp, out n))
            {
                strTemp.Add(sTemp);
                sTemp = string.Empty;
            }

            string res = string.Empty;
            //循环比较长度
            for (int i = 0; i < strTemp.Count; i++)
            {
                for (int j = i + 1; j < strTemp.Count; j++)
                {
                    if (strTemp[i].Length > strTemp[j].Length)
                        res = strTemp[i];
                    else
                        res = strTemp[j];
                }
            }

            Response.Write(res);
        }


后来,一哥们给了我个好建议,使用正则直接搞定,然后进行排序即可搞定

 

/// <summary>
        /// 方法二(正则、list排序)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn2_Click(object sender, EventArgs e)
        {
            string str = tbStr.Text;
            Regex rgx = new Regex("[\\d+]+");
            MatchCollection mc = rgx.Matches(str);
            List<Match> ms = new List<Match>();
            foreach (Match m in mc)
            {
                ms.Add(m);
            }


            ms.Sort(delegate(Match a, Match b)
            {
                return a.Length.CompareTo(b.Length);
            });

            Response.Write(ms[ms.Count - 1].Value);
        }


还学习了下List的排序

 

收获不小吐舌头

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值