关键代码:
class="csharpcode"> #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>(@"Yan Zhi wei", _actual); }
结果:
希望有所帮助!