下面有一個字符串陣列:
string[] elements = {"adsf","etwert" ,"asdfasd","gs"};
要求是獲取元素最長或最短的長度。
你可以在程序中創建一個對象,這個對象有兩個屬性元素值和元素長度:
source code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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; } } |
接下來,我們可以創建另一個對象:
#1c5d70a93df662bdc820d2c9f3078d2c#
source code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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#實現獲取字符串陣列中元素最長或最短的長度就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/insus/p/7985103.html