asp.net中自带的CutString只能截取字符数量的长度,但中英文字符数有差异,一个中文字等同于二个英文字符的宽度,这样对截取后的效果不理想.使用以下的方法就能解决.


using System;
using System.Collections.Generic;
using System.Text;
namespace BLL
{
public class CutStr
{
public static string CutString(string str, int length)
{
if (str == "" )
{
str = "没有信息";
}
else
{
int i = 0, j = 0;
foreach (char chr in str)
{
if ((int)chr > 127)
{
i += 2;
}
else
{
i++;
}
if (i > length)
{
str = str.Substring(0, j) ;
//str = str.Substring(0, j) + "...";
break;
}
j++;
}
}
return str;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace BLL
{
public class CutStr
{
public static string CutString(string str, int length)
{
if (str == "" )
{
str = "没有信息";
}
else
{
int i = 0, j = 0;
foreach (char chr in str)
{
if ((int)chr > 127)
{
i += 2;
}
else
{
i++;
}
if (i > length)
{
str = str.Substring(0, j) ;
//str = str.Substring(0, j) + "...";
break;
}
j++;
}
}
return str;
}
}
}