public class StringFormat { public StringFormat() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> /// 取指定长度的的字符串(中文字符当两个字符,当出现半个中文字符当一个中文处理) /// </summary> /// <param name="str">要处理的字符串</param> /// <param name="length">要截取的字符串长度</param> /// <returns>截取后的字符串</returns> public string GetFrontString(string str,int length) { if (length > System.Text.Encoding.Default.GetByteCount(str) ) { throw new ArgumentOutOfRangeException("the countIndex big than the string length"); } if (length < 0) { throw new ArgumentOutOfRangeException("the countIndex less than zero"); }
int count = 1; string returnStr = ""; char[] chr = str.ToCharArray(); for (int i = 0; i < chr.Length; i++) { if (count > length) break; int tmp =(int)chr[i]; if (tmp < 0) { tmp += 65535; } if (tmp > 255) { count += 2; } else { count ++; } returnStr += chr[i]; } return returnStr; }}
以上是类里的方法,调用事件语句这里 if (System.Text.Encoding.Default.GetByteCount(Strlb1)>44) {
{
public StringFormat()
{
//
// TODO: 在此处添加构造函数逻辑
//
} /// <summary>
/// 取指定长度的的字符串(中文字符当两个字符,当出现半个中文字符当一个中文处理)
/// </summary>
/// <param name="str">要处理的字符串</param>
/// <param name="length">要截取的字符串长度</param>
/// <returns>截取后的字符串</returns>
public string GetFrontString(string str,int length)
{
if (length > System.Text.Encoding.Default.GetByteCount(str) )
{
throw new ArgumentOutOfRangeException("the countIndex big than the string length");
}
if (length < 0)
{
throw new ArgumentOutOfRangeException("the countIndex less than zero");
}
int count = 1;
string returnStr = ""; char[] chr = str.ToCharArray();
for (int i = 0; i < chr.Length; i++)
{
if (count > length) break;
int tmp =(int)chr[i];
if (tmp < 0)
{
tmp += 65535;
}
if (tmp > 255)
{
count += 2;
}
else
{
count ++;
}
returnStr += chr[i];
}
return returnStr;
}}
if (System.Text.Encoding.Default.GetByteCount(Strlb1)>44)
{
StringFormat SF=new StringFormat();
((Label)e.Item.Cells[6].FindControl("Label2")).Text=SF.GetFrontString(Strlb1,44)+"...";
}Strlb1就是你要判断的字符串,我这里是判断当英文字符大于44个时(汉字大于22个时),调用.绝对可以用的.
/// 字符长度控制 中文 英文识别!
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
bool lenString(string str, int len)
{
byte[] sarr = System.Text.Encoding.Default.GetBytes(str); if(sarr.Length > len)
return false;
else
return true;
}
{
int digit = 0 ;
for (int i =0 ;i<CString.Length ; i++)
{
if (Convert.ToInt32(Convert.ToChar(CString.Substring(i,1)))<Convert.ToInt32(Convert.ToChar(128)))
{
digit+=1;
}
else
{
digit+=2;
}
}
if (digit > 10)
{
return false ;
}
else
{
return true ;
}
}