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

比如一个字符串"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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值