如何将新闻正文中的“微软”加上链接?而数据库里并没此链接。。像新浪新闻那样,关键词自动加上链接。我用Regex类中的Replace试了一下,全所有正文中的“微软”都替换了,有什么方法只替换第一个?应该如何实现?

解决方案 »

  1.   

    string  content = " 微软 Microsoft is a software provider  " ;
    int startIndex  = content.IndexOf("微软") + 2 ;string Result = content.SubString( 0 ,startIndex ).Replace( "微软" ,"<a href='Microsoft.com'>"  ) + content.SubString( startIndex ) ;
      

  2.   

    我记着在javascript中默认就是只替换一个,不过可以设置全局替换。。C#中难道就没有一种更简单的方法只替换第一个吗?
      

  3.   

    我改成这样了,,大家看看有没有什么好的方法,或是通用的方法:
    string GsKeywords(string content){
    string strC=content;
    Hashtable ht = new Hashtable();
    ht.Add("微软","http://www.microsoft.com");
    ht.Add("大河报","http://www.dahedaily.com");
    ht.Add("奥迪","http://www.audi.com.cn");
    ht.Add("大众汽车","http://www.vw.com.cn");
    ht.Add("上海大众","http://www.csvw.com");
    ht.Add("郑州世纪鸿图丰田","http://auto.i-style.cn/sjft");
    ht.Add("河南弘通","http://www.hn-auto.com/htm6/index.php");
    ht.Add("上汽通用五菱","http://www.sgmw.com.cn");
    ht.Add("福特公司","http://www.ford.com.cn");
    ht.Add("奇瑞汽车","http://www.chery.cn");
    ht.Add("北京现代","http://www.beijing-hyundai.com.cn");
    IDictionaryEnumerator ie = ht.GetEnumerator();
    int i=0;
    while(ie.MoveNext()){
    i=strC.IndexOf(ie.Key.ToString());
    if(i!=-1){
    strC = strC.Substring(0,i) + "<a class=\"keyword NrTxt\" href=\""+ie.Value+"\" Target=\"_blank\">" + ie.Key+ "</a>" + strC.Substring(i+ie.Key.ToString().Length);
    }
    }
    //strC = Regex.Replace (strC,ie.Key.ToString(),"<a class=\"keyword NrTxt\" href=\""+ie.Value+"\" Target=\"_blank\">" + ie.Key + "</a>",RegexOptions.None);
    return strC;
    }
      

  4.   

    楼上的方法也不错!
    不过用Replace(content,"微软","<a herf=http://www.microsoft.com>微软</a>")的方法比较简单易懂。
      

  5.   

    替换是根本。====CSDN 小助手 V2.5 2005年11月05日发布====
    CSDN小助手是一款脱离浏览器也可以访问Csdn论坛的软件
    界面:http://blog.csdn.net/Qqwwee_Com/archive/2005/11/05/523395.aspx
    下载:http://szlawbook.com/csdnv2
      

  6.   

    这样不是给服务器端增加压力么
    有没有 用 JavaScript 在客户端加链接标记的方法?