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

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

     /// <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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值