C# line break every n characters

后端 未结 5 932
孤街浪徒
孤街浪徒 2020-12-16 20:39

Suppose I have a string with the text: \"THIS IS A TEST\". How would I split it every n characters? So if n was 10, then it would display:

\"THIS IS A \"
\"T         


        
5条回答
  •  生来不讨喜
    2020-12-16 21:14

    Let's borrow an implementation from my answer on code review. This inserts a line break every n characters:

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

    Edit:
    To return an array of strings instead:

    public static string[] SpliceText(string text, int lineLength) {
      return Regex.Matches(text, ".{1," + lineLength + "}").Cast().Select(m => m.Value).ToArray();
    }
    

提交回复
热议问题