简单的搜索高亮类


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace siteadmin
{
public class search
{
public enum enStyle : int
{
red = 1,
black = 2,
yellow = 3,
white = 4,
blue = 5,
green = 6,
other = -1
}


private static string[] colorStr = new string[] { "red", "black", "yellow", "white", "blue", "green" };

public static string otherBKColor;
public static string OtherBKColor
{
set { otherBKColor = value; }
}

public static string otherPenColor;
public static string OtherPenColor
{
set { otherPenColor = value; }
}
/// <summary>
/// 高亮搜索内容高亮显示类
/// </summary>
/// <param name="content">内容</param>
/// <param name="key">搜索键</param>
/// <param name="maxLenght">string最大长度,-1为关闭</param>
/// <param name="colorStyle">样式</param>
/// <param name="endString">结尾字符</param>
/// <returns></returns>
public static string highLightStr(string content, string key, int maxLenght, enStyle BKcolorStyle, enStyle penColorStyle, string endString)
{
if (content.Length <= 0 || key.Length <= 0)
{
return content;
}


string staSpan = null;
if ((int)BKcolorStyle == -1)
{
staSpan = "<span style='background-color:" + otherBKColor + ";color:" + otherPenColor + "'>";
}
else
{
staSpan = "<span style='background-color:" + colorStr[(int)BKcolorStyle - 1] + ";color:" + colorStr[(int)penColorStyle - 1] + "'>";

}
string endSpan = "</span>";


int temp = System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(content, key, System.Globalization.CompareOptions.IgnoreCase);

if (temp >= 0)
{
if (maxLenght != -1)
{

if(content.Length>maxLenght)
{
//1.如果关键字前面有maxLenght/2的字符串
if (temp > maxLenght / 2)
{
//获取截取开头位置索引
int staIndex=temp-(maxLenght/2);
//开头索引足够截取到maxLength个字符串
if(content.Length-staIndex>maxLenght)
{
content=content.Substring(staIndex,maxLenght);
}
//后面的不够截取
else
{
//需要往前移动的位数
int i=maxLenght-(content.Length-staIndex);
//往前移动
staIndex=staIndex-i;
content=content.Substring(staIndex,maxLenght);
}
}

else
{
content=content.Substring(0,maxLenght);
}
}



}
temp = System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(content, key, System.Globalization.CompareOptions.IgnoreCase);
content = content.Insert(temp, staSpan);
content = content.Insert(staSpan.Length + temp + key.Length, endSpan);

}


return content + endString;

}


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值