How to split string preserving whole words?

前端 未结 10 2296
梦谈多话
梦谈多话 2020-11-30 09:18

I need to split long sentence into parts preserving whole words. Each part should have given maximum number of characters (including space, dots etc.). For example:

10条回答
  •  心在旅途
    2020-11-30 09:36

    While CsConsoleFormat† was primarily designed to format text for console, it supports generating plain text as well.

    var doc = new Document().AddChildren(
      new Div("Silver badges are awarded for longer term goals. Silver badges are uncommon.") {
        TextWrap = TextWrapping.WordWrap
      }
    );
    var bounds = new Rect(0, 0, 35, Size.Infinity);
    string text = ConsoleRenderer.RenderDocumentToText(doc, new TextRenderTarget(), bounds);
    

    And, if you actually need trimmed strings like in your question:

    List lines = text.Trim()
      .Split(new[] { Environment.NewLine }, StringSplitOptions.None)
      .Select(s => s.Trim())
      .ToList();
    

    In addition to word wrap on spaces, you get proper handling of hyphens, zero-width spaces, no-break spaces etc.

    † CsConsoleFormat was developed by me.

提交回复
热议问题