通过关键字高亮文本内容的算法 - ToHighLightStr

2017-05-30 10:00:02  访问(1335) 赞(0) 踩(0)

  • 
        /// <summary>
        /// 通过关键字高亮文本内容的算法 - ToHighLightStr
        /// </summary>
        /// <param name="str"></param>
        /// <param name="kw"></param>
        /// <returns></returns>
        protected string ToHighLightStr(string str, string kw)
        {
            if (str == null)
                return "";
    
            if (kw == null || kw.Length == 0)
                return str;
    
            string lowerStr = str.ToLower();
            string lowerKw = kw.ToLower();
    
            StringBuilder theResult = new StringBuilder();
            int idx = -1;
            string strPre = null;
            string strHL = null;
            string strPost = null;
            int kwLen = kw.Length;
    
            while (true)
            {
                idx = lowerStr.IndexOf(lowerKw);
    
                if (idx == -1)
                {
                    // 没有找到记录 //
                    theResult.Append(str);
                    break;
                }
    
                strPre = str.Substring(0, idx);
                strHL = str.Substring(idx, kwLen);
                strPost = str.Substring(idx + kwLen);
    
                theResult.Append(strPre);
                theResult.Append("<font color=\"red\">" + strHL + "</font>");
    
                str = strPost;
                lowerStr = lowerStr.Substring(idx + kwLen);
            }
    
            return theResult.ToString();
        }
    
  • 输入 :
    关键字 :
    输出:

上一条:

下一条:


 

相关评论

评论加载中……
 

发表评论

类型:
内容:
  (Alt+Enter)