The string breaks the string into x number of characters, but not through the word

I will try to explain what I am looking for as much as possible. I am currently using this code to break a line every x number of characters.

public static string SpliceText(string text, int lineLength) { return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine); } 

This works fine, but often it breaks every number x and, obviously, sometimes breaks a word. Is it possible for the code to check if it violates the word in the middle of the word, and if it does not break at all, but now check if the first character after the break is a space and removes it, if so?

I know that I ask a lot, but thanks in advance!

+4
source share
1 answer

Try the following:

 public static string SpliceText(string text, int lineLength) { var charCount = 0; var lines = text.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries) .GroupBy(w => (charCount += w.Length + 1) / lineLength) .Select(g => string.Join(" ", g)); return String.Join("\n", lines.ToArray()); } 

Here is my screenshot for this: enter image description here

+13
source

Source: https://habr.com/ru/post/1482495/


All Articles