作个把字符插入到一个按升序排序的字符串中的方法

前段时间做的个小东东里面,需要建立一个字符索引,就是一个字符串,该串里面的每个字符都可以作为索引.
并且这个字符串还要是升序排列.我左看右看,发现string里面也没有sort功能.array倒是有sort功能,那难道我把字符串里面的字符一个个取出来放到一个array里面再sort?我不愿意这么作,就在工具类里面写了两个函数来实现,代码如下,大家参考一下.主要是用二分法来实现位置的查找,然后再在合适的位置插入.
namespace Tools.Module
{
public class Tools
{
public Tools()
{
}

public static string GetStrFromStr(string src,int Index)
{
if(src.IndexOf(",")==0) src = src.Remove(0,1);
for(int i=0;i

 1<index;i++) <summary="" else="" if(src.indexof(",")<0)="" return="" src='src.Remove(0,1+src.IndexOf(","));' src.substring(0,src.indexof(","));="" src;="" {="" }="">   
 2/// 计算出某字符在一个升序排序字符串中应处的位置.   
 3///    
 4/// <param name="src"/>字符串   
 5/// <param name="c"/>字符   
 6/// <returns>该字符应处的位置</returns>   
 7public static int GetTheSortedIndex(string str,char c)   
 8{   
 9int iLength = str.Length;   
10if(iLength == 0) return 0;   
11if(iLength == 1 &amp;&amp; str[0] &gt;= c) return 0;   
12else if(iLength == 1 &amp;&amp; str[0] &lt; c) return 1; 
13
14int index = iLength/2;   
15if(str[index]&gt;c)   
16{   
17return GetTheSortedIndex(str.Substring(0,index),c);   
18}   
19else if(str[index]<c) <summary="" else="" index+1+getthesortedindex(str.substring(index+1,ilength-index-1),c);="" index;="" return="" {="" }="">   
20/// 把一个字符插入到一个升序排列的字符串中   
21///    
22/// <param name="c"/>要插入的字符   
23/// <param name="str"/>目的字符串   
24public static void InsertCharIntoSortedString(char c,ref string str)   
25{   
26if(str==null || str.Length==0 )   
27{   
28str=c.ToString();   
29return;   
30} 
31
32for(int i=0;i&lt;str.Length;i++)   
33{   
34if(str[i]==c) return;   
35}   
36  
37int index = GetTheSortedIndex(str,c);   
38str = str.Insert(index,c.ToString());   
39}   
40}   
41}   
42![](http://dev.csdn.net/Emoticons/red_smile.gif) 见笑见笑 ![](http://dev.csdn.net/Emoticons/tongue_smile.gif)</c)></index;i++)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus