- #region 控制字符串长度
- /// <summary>
- /// 替换超出规定长度字符串为"..."
- /// </summary>
- /// <param name="str">实际取出的字符串</param>
- /// <param name="len">规定的长度,单位为byte</param>
- /// <returns>替换后的字符串</returns>
- public static string substr(string str, int len)
- {
- //去处字符串2边的空格
- str = str.Trim();
- //创建一个byte数组接受转化为byte类型的字符串,因为中英文长度不同,所以统一用byte
- byte[] myByte = System.Text.Encoding.Default.GetBytes(str);
- //如果长度超过设定的长度,截取未超出的字符串拼接"..."返回
- if (myByte.Length > len)
- {
- string result = "";
- for (int i = 0; i < str.Length; i++)
- {
- byte[] tempByte = System.Text.Encoding.Default.GetBytes(result);
- if (tempByte.Length < len)
- {
- result += str.Substring(i, 1);
- }
- else
- {
- break;
- }
- }
- return result + "...";
- }
- //未超出,原样返回
- else
- {
- return str;
- }
- }
- #endregion
- 原创:http://blog.csdn.net/m2j1984/article/details/5541482
控制字符串长度(中英文保持一致) .
最新推荐文章于 2023-04-07 09:11:19 发布