/// <summary>
/// 返回指定长度的字符(区分中英文)
/// </summary>
/// <param name="inputStr">要截取的字符</param>
/// <param name="len">要保留的长度</param>
/// <param name="IsAppendWord">是否附加内容</param>
/// <param name="appendWord">如果IsAppendWord为真,则附加此内容</param>
/// <returns></returns>
private string GetTrimStrWithLenAndCn(string inputStr, int len,bool IsAppendWord,string appendWord )
{
if (string.IsNullOrEmpty(inputStr)) return "";
bool istrim = false;//记录是否截断过
//先截取一次
if (inputStr.Length > len)
{
inputStr = inputStr.Substring(0, len);
istrim = true;
}
//一个中文当两个字符
Regex regcn = new Regex(@"^[\u2E80-\u9FFF]+$");
int nlen = 0;
int n = 0;//计算得出的长度
for (int i = 0; i < inputStr.Length && n<len; i++)
{
if (regcn.IsMatch(inputStr[i].ToString()))
{
n += 2;
nlen += 1;//出现次数
}
else
{
n += 1;
}
}
//出现几次,截取长度应该减几
if (nlen > 0)
{
if (inputStr.Length + nlen > len)
{
inputStr = inputStr.Substring(0, len-nlen);
istrim = true;
}
}
if (istrim && IsAppendWord)
{
inputStr += appendWord;
}
return inputStr;
}
JS方法:
/*#########区分中英文截取#########*/
/*#inputstr:要截取的字符##########*/
/*#length:要保留的长度#*/
/*#isAppend:是否附加内容#*/
/*#appendStr:要附加的内容#*/
function TrimStrWithCnAndEn(inputstr, length, isAppend, appendStr) {
if (inputstr == undefined || inputstr == "") {
return "";
}
var istrim = false;//是否截取过
if (inputstr.length > length) {
inputstr = inputstr.substring(0, length);
istrim = true;
}
var reg = /^[\u2E80-\u9FFF]+$/;
var nlen = 0;
var n = 0; //计算得出的长度
for (var i = 0; i < inputstr.length && n < length; i++) {
var ss = inputstr.charAt(i);
var b = reg.test(ss);
if (b)
{
n += 2;
nlen += 1;//出现次数
}
else
{
n += 1;
}
}
//出现几次,截取长度应该减几
if (nlen > 0)
{
if (inputstr.length + nlen > length) {
inputstr = inputstr.substring(0, length - nlen);
istrim = true;
}
}
if (istrim && isAppend)
{
inputstr += appendStr;
}
return inputstr;
}