Search code examples
c#stringconsole-applicationline-breaks

How to output string text so there’s no line breaks with words in C#


I’ve been searching on here and I’m developing a chatbot that has various responses, some of the responses are pretty long strings. Is there any way to make sure that line breaks don’t occur mid-word in the output? Would I have to insert it in my code before every response or define it before the method begins? Or is this just not possible? Thanks.


Solution

  • There is no built-in way to format string to fit console.

    You need to decide what is the criteria for your line breaking algorithm and implement that.

    Notes

    • you need to re-calculate it every time you render the text (assuming you have some sort of history shown) as window size can change (you can resize console windows similar to all other windows thus changing character-width).
    • depending on the language finding boundaries of words could range from trivial to implement ("just use spaces") to multiyear research project for once that don't use spaces (range similar to xkcd:Tasks :)).

    If you have options I'd recommend switching to HTML rendering instead of console as word breaking already done there for you (and much more like proper emojis which you will have hard time with in console app)