System Information

Impossible Is Nothing...

导航

截取中文和英文长度的问题

byte[] FixedLen = new byte[10];
Array.Copy(System.Text.Encoding.Default.GetBytes("中华人民共和国万岁"), FixedLen, 10);
Console.WriteLine(System.Text.Encoding.Default.GetString(FixedLen));


/// <summary>
/// 按字符串实际长度截取定长字符窜
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="length">要截取的长度</param>
/// <returns>string型字符串</returns>
public static string GetString(string str, int length)
{
 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) + "...";
   break;
  }
  j ++;
 }
 return str;
 
}

posted on 2005-06-20 17:17  SysInfo  阅读(945)  评论(0编辑  收藏  举报