编程乐趣:一个强制换行的小方法

来源:互联网 发布:利用excel建立数据库 编辑:程序博客网 时间:2024/06/04 22:57

前段时间做了个功能,用打印机打印内容。打印是这种格式:
项目名:内容;
由于打印的使用的那种纸宽度有限,所以要考虑到换行于是写了个给字符串换行的功能,试了一下貌似还能用,分享分享,希望能有所帮助。

     /// <summary>        /// 格式化字符格式        /// </summary>        /// <param name="printContent">内容</param>        /// <param name="itemName">题目</param>        /// <param name="lineLength">每行长度</param>        /// <returns></returns>        private static string FormatPrintLine(string printContent, string itemName, int lineLength)        {            List<string> contentRows = new List<string>();            string formathContent = string.Empty;            if (printContent.Length <= lineLength)            {                return itemName + printContent;            }            int index = 0;            string space = string.Empty;            for (int i = 0; i < itemName.Length; i++)            {                Match match = new Regex(@"[\u4E00-\u9FA5]|[\uFE30-\uFFA0]", RegexOptions.IgnoreCase).Match(itemName[i].ToString());                space += match.Success ? "  " : " ";//中文占2字符            }            do            {                if (contentRows.Count > 0)                {                    if (((printContent.Length - (contentRows.Count * lineLength))) / lineLength > 0)                    {                        contentRows.Add(space + printContent.Substring(contentRows.Count * lineLength, lineLength) + Environment.NewLine);                    }                    else                    {                        contentRows.Add(space + printContent.Substring(contentRows.Count * lineLength, printContent.Length -                            (contentRows.Count * lineLength)) + Environment.NewLine);                    }                }                else                {                    contentRows.Add(itemName + printContent.Substring(0, lineLength) + Environment.NewLine);                }                index += lineLength;            } while (index < printContent.Length);            for (int i = 0; i < contentRows.Count; i++)            {                formathContent += contentRows[i];            }            return formathContent;        }

调用:

 static void Main(string[] args)        {            string itemName = "内容:";            string content = @" 巴西国家队昨天打进的中国国家队的所有进球完全是非法的、无效的,丝毫改变不了中国球员实力超群的事实,"+                " 丝毫改变不了中国队在国际足坛的霸主地位。中国球员强烈敦促巴西国家队立即停止一切损害中国球门的行为,如果巴西国家队一意孤行,"+                "由此在场上中国球员所造成的一切严重后果只能由巴西国家队承担。";            string result = FormatPrintLine(content,itemName,20);            Console.WriteLine(result);            Console.ReadKey();        }

效果:

 

代码下载:http://download.csdn.net/detail/yysyangyangyangshan/4568386

原创粉丝点击