软件编程
位置:首页>> 软件编程>> C#编程>> c#实现获取字符串阵列中元素最长或最短的长度

c#实现获取字符串阵列中元素最长或最短的长度

作者:杨明波(Leo Yang)  发布时间:2022-08-22 08:54:01 

标签:字符串,阵列,元素,最长,最短,长度

下面有一个字符串阵列:

string[] elements = {"adsf","etwert" ,"asdfasd","gs"};

要求是获取元素最长或最短的长度。

你可以在程序中创建一个对象,这个对象有两个属性元素值和元素长度:

c#实现获取字符串阵列中元素最长或最短的长度

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;  
 }
}

接下来,我们可以创建另一个对象:

c#实现获取字符串阵列中元素最长或最短的长度

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()。

现在,我们在控制台应用程序,测试一下我们的上面写的代码:

 c#实现获取字符串阵列中元素最长或最短的长度

Ok,已经达到我们预期的结果。

但是,根据程序的封装,下面高亮部分的代码,不应该出现在客户端的程序中。怎样处理的,应该封装在Class7这个类别中。因此,Insus.NET想改动它。

c#实现获取字符串阵列中元素最长或最短的长度

经过这样一改,前端代码直接把阵列字符串传入即可:

c#实现获取字符串阵列中元素最长或最短的长度

来源:http://www.cnblogs.com/insus/p/7985103.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com