从字符串数组中把数字的元素找出来
下面这个字符串数组:
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; } }
在类别中,添加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(); }
string[] str = { "3","y","34","QQ","41","adsf4","7","52"}; var result = new List<Digit>(); 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()); }