字符串数组排序在程序中很常用,今天分享一种排序方法。
以前在ASP中对字符串数组的排序方法是快速排序或冒泡排序来遍历排序,总觉得这样效率不是很高。我用ADODB来排序,具体代码如下:
' 对字符串进行排序
' s:字符串
' ss: 分隔符
' ob: 排序方式(desc | asc)
'return 排列好的字符串
Function StrOrderBy(ByVal s, ByVal ss, ByVal ob)
Dim Rs
Dim i
Dim res, ts
ob = LCase(ob)
ts = Split(s, ss) '分割字符串,变成数组
If ob <> "asc" Then ob = "desc" Else ob = "asc" End If '排序方式
Set Rs = Server.CreateObject("ADODB.Recordset")
rs.CursorLocation = 1
rs.CursorType = 1
rs.Fields.Append "strname",200,255
rs.open
'写入到临时表
For i = 0 To UBound(ts)
rs.addnew
If Not isnullorempty(ts(i)) Then
rs.Fields("strname") = ts(i)
End If
rs.update
Next
'排序方式
rs.Sort = "strname " & ob
If Not Rs.Eof Then
'移到第一位
rs.MoveFirst
'循环输出数组
do while not rs.EOF
res = res & Rs("strname") & ss
Rs.MoveNext
Loop
End If
Rs.Close
Set rs = Nothing
StrOrderBy = res
End Function
主要是通过记录集(Recordset)创建临时表,把数组输入临时表内,然后通过Order By来排序,然后输出。
在C#中有个更简单的方法,代码如下:
string[] strs = new string[] { };
string str = textBox1.Text; //获取输入字符,格式:af,e43,fefd,45,gfe,fsdf3
if (str.Length > 0)
{
strs = str.Split(','); //分割字符,输入到数组
}
ArrayList al = new ArrayList(strs); //把数组存入ArrayList
al.Sort(); //排序
//循环输入
foreach (string a in al)
{
textBox2.Text += "\r\n" + a;
}
这里用到了ArrayList的Sort()方法,是使用快速排序法(链接地址:http://www.rainsts.net/article.asp?id=695),欢迎大家发表自己的看法。
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array array)
{
// ...
Sort(array, null, array.GetLowerBound(0), array.Length, null);
}
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array keys, Array items, int index, int length, IComparer comparer)
{
// ...
if ((length > 1) && (((comparer != Comparer.Default) && (comparer != null)) || ... ))
{
object[] objArray = keys as object[];
object[] objArray2 = null;
if (objArray != null)
{
objArray2 = items as object[];
}
if ((objArray != null) && ((items == null) || (objArray2 != null)))
{
new SorterObjectArray(objArray, objArray2, comparer).QuickSort(index, (index + length) - 1);
}
else
{
new SorterGenericArray(keys, items, comparer).QuickSort(index, (index + length) - 1);
}
}
}
转载自 寒秋博客 来源
若转载请注明出处: Spirit's Home
本文地址: http://www.7788sky.cn/post/Csharp_for_string_sorting.html
1 Response to “C#对字符串数组排序”
By Merrywdress2011 on 2011-11-5 15:42:55| http://www.idresshop.com
没有找到c#的arraylist的排序方法