在网页开发中,会遇到中英文占位宽度不一导致页面字符不一的情况,虽然是个很小的问题,但是经常会遇到。下面是函数源码。 /// <summary> /// 根据传入的string 切去指定的长度(区分中文和英文(中文占用两个字符而英文占用1个字符位置)) /// </summary> /// <param name="str">原字符串</param> /// <param name="len">切去的长度</param> /// <param name="spCh">是否考虑中英文占位宽度不一</param> /// <returns></returns> public static string cutStr(string str, int len, bool spCh) { if (spCh)//考虑中英文 { int strCount = str.Length; int MaxLen = len * 2; if (strCount > MaxLen)//超了即使都是字符的最大限度 { str = str.Substring(0, MaxLen);//切取 } string reStr = ""; for (int i = 0; i < str.Length; i++) { int count = 0; if (IsHZ(str[i].ToString()))//如果是汉字 { count = 2; } else { count = 1; } if (MaxLen>= 2)//剩余的位置大于等于0 { reStr += str[i].ToString(); } else if (MaxLen == 1) { if (!IsHZ(str[i].ToString())) { reStr += str[i].ToString(); } } MaxLen -= count;//计算剩下的位置 } return reStr; } else { if (str.Length > len) { str = str.Substring(0, len); } return str; } } /// <summary> /// 检查是否为汉字 /// </summary> /// <param name="s"></param> /// <returns></returns> public static bool IsHZ(string s) { byte[] b = System.Text.Encoding.Default.GetBytes(s); if (b.Length > 1) { return true; } else { return false; } }