下面有一个字符串阵列:
string[] elements = {"adsf","etwert" ,"asdfasd","gs"};
要求是获取元素最长或最短的长度。
你可以在程序中创建一个对象,这个对象有两个属性元素值和元素长度:
Source Code
class Class6 {
private string _ElementValue;
public string ElementValue {
get {
return _ElementValue;
}
set {
_ElementValue = value;
}
}
public int ElementLength {
get {
return _ElementValue.Length;
}
}
public Class6(string v) {
_ElementValue = v;
}
}
接下来,我们可以创建另一个对象:
Source Code
class Class7 {
private List<Class6> Elements = new List<Class6>();
public void Add(Class6 c6) {
Elements.Add(c6);
}
public int MaxLenth() {
int max = int.MinValue;
foreach (Class6 c6 in Elements) {
if (c6.ElementLength > max) {
max = c6.ElementLength;
}
}
return max;
}
public int MinLenth() {
int min = int.MaxValue;
foreach (Class6 c6 in Elements) {
if (c6.ElementLength < min) {
min = c6.ElementLength;
}
}
return min;
}
}
上面的对象中,它有3个public的方法,Add(),MaxLength()和MinLength()。
现在,我们在控制台应用程序,测试一下我们的上面写的代码:
Ok,已经达到我们预期的结果。
但是,根据程序的封装,下面高亮部分的代码,不应该出现在客户端的程序中。怎样处理的,应该封装在Class7这个类别中。因此,Insus.NET想改动它。
经过这样一改,前端代码直接把阵列字符串传入即可:
以上这篇c#实现获取字符串阵列中元素最长或最短的长度就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- C#算法函数:获取一个字符串中的最大长度的数字
- C#区分中英文按照指定长度截取字符串的方法
- C#截取中英文混合指定长度字符串实例
- c#固定长度的随机字符串例子
- 超简单C#获取带汉字的字符串真实长度(单个英文长度为1,单个中文长度为2)