栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

从字符串数组中把数字的元素找出来

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从字符串数组中把数字的元素找出来

下面这个字符串数组:

 string[] str = { "3","y","34","QQ","41","adsf4","7","52"};


实现这个要求的方法也许会很多。下面Insus.NET使用一个通用的方法来实现:
面向对象,创建一个类别Class Digit:

 

  class Digit    {        private int _D;        public int D        {            get { return _D; }            set { _D = value; }        }        public Digit(int digit)        {            this._D = digit;        }    }

Source Code

 

在类别中,添加2个方法,一是判断元素是否为数字,另一个是是重写ToString()方法:

 

 public static bool TryParse(string str, out Digit digit)        {            digit = null;            if (string.IsNullOrEmpty(str))                return false;            int i;            if (!int.TryParse(str, out i))                return false;            digit = new Digit(i);            return true;        }        public override string ToString()        {            return _D.ToString();        }

Source Code

 

 方法已经实现,可以在控制台中测试一下:

 string[] str = { "3","y","34","QQ","41","adsf4","7","52"};            var result = new List();            foreach (string s in str)            {                Digit d;                if (Digit.TryParse(s, out d))                    result.Add(d);            }            foreach (Digit d in result)            {                Console.WriteLine(d.ToString());            }

Source Code

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/231745.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号