ips99

ASP.NET截取字符串函数

#region 截取指定字数字符串
        /// <summary>
        /// 格式化字符串,取字符串前 strLength 位,其他的用...代替.
        /// 计算字符串长度。汉字两个字节,字母一个字节
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="strLength">字符串长度</param>
        /// <returns></returns>
        public static string FormatStr(string str, int len)
        {
            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                { tempLen += 2; }
                else
                { tempLen += 1; }
                try
                { tempString += str.Substring(i, 1); }
                catch
                { break; }
                if (tempLen > len) break;
            }
            //如果截过则加上半个省略号 
            byte[] mybyte = System.Text.Encoding.Default.GetBytes(str);
            if (mybyte.Length > len)
                tempString += "......";
            tempString = tempString.Replace(" ", " ");
            tempString = tempString.Replace("<", "<");
            tempString = tempString.Replace(">", ">");
            tempString = tempString.Replace('\n'.ToString(), "<br>");
            return tempString;
        }        #endregion
ASP.NET截取字符串函数
posted @   迷途小石头  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示