首页 > 代码库 > [C#]文字换行

[C#]文字换行

关键代码:

     #region 文字换行        /// <summary>        /// 文字换行        /// <para>eg:StringHelper.WrapText("YanZhiwei", 3);==>"Yan\r\nZhi\r\nwei"</para>        /// </summary>        /// <param name="data">需要换行的文字</param>        /// <param name="maxWidth">多少长度换行</param>        /// <returns>换行好的文字</returns>        public static string WrapText(this string data, int maxWidth)        {            int _stringCount = data.Length;            if (maxWidth > 0 && _stringCount > maxWidth)            {                StringBuilder _builderString = new StringBuilder(data);                int _breakCount = _builderString.Length / maxWidth;                for (int i = 0; i < _breakCount; i++)                {                    int _insertPosition = i * maxWidth;                    if (_insertPosition != 0)                    {                        int _offset = (i - 1) * 2;//(\r\n)                        _builderString.Insert(_insertPosition + _offset, Environment.NewLine);                    }                }                return _builderString.ToString();            }            else            {                return data;            }        }        #endregion

测试:

        [TestMethod()]        public void WrapTextTest()        {            string _actual = StringHelper.WrapText("YanZhiwei", 3);            Assert.AreEqual<string>(@"YanZhiwei", _actual);        }

<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>结果:

image

希望有所帮助!

<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

[C#]文字换行