计算字符串中各个字符串出现的次数

比如一个字符串"a,b,a,c,b,b,d",现在我们要统计每个字符串出现次数。解决这个问题,我们可以使用泛型集合 Dictionary(TKey,TValue)。它有一个key值用来存储字符串和一个value值,用来存储字符串出现的次数。

实现第一步,需要把字符串分割为一个array,需要使用到的函数Split():

string[] arr = s.Split ( ' , ');

 

第二步,用Dictionary(TKey,TValue)实例化。

Dictionary< stringint> Statistics =  new Dictionary< stringint>();

 

第三步,统计:

  foreach ( string w  in arr)
        {
             if (Statistics.ContainsKey(w))
            {
                Statistics[w] +=  1;
            }
             else
            {
                Statistics[w] =  1;
            }
        }

 

写完以上代码算是大功告成。

但Insus.NET还是要把统计的结果显示出来:

.aspx:

计算字符串中各个字符串出现的次数 View Code
  < asp:Repeater  ID ="Repeater1"  runat ="server" >
             < HeaderTemplate >
                 < table  border ="1"  cellpadding ="1"  cellspacing ="0" >
                     < tr >
                         < td >字符  </ td >
                         < td >次数  </ td >
                     </ tr >
             </ HeaderTemplate >
             < ItemTemplate >
                 < tr >
                     < td >
                         <% Eval ( " key " %>
                     </ td >
                     < td >
                         <% Eval ( " value " %>
                     </ td >
                 </ tr >
             </ ItemTemplate >
             < FooterTemplate >
                 </ table >
             </ FooterTemplate >
         </ asp:Repeater >

 

.aspx.cs:

计算字符串中各个字符串出现的次数 View Code
  protected  void Page_Load( object sender, EventArgs e)
    {
         this.Repeater1.DataSource = Statistics;
         this.Repeater1.DataBind();
    }

 

结果:

 计算字符串中各个字符串出现的次数

 

如果你想看看MS SQL Server版本: http://www.cnblogs.com/insus/archive/2012/02/23/2364580.html

 

 

你可能感兴趣的:(字符串)