C# line break every n characters

后端 未结 5 924
孤街浪徒
孤街浪徒 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条回答
  •  萌比男神i
    2020-12-16 21:19

    Coming back to this after doing a code review, there's another way of doing the same without using Regex

    public static IEnumerable SplitText(string text, int length)
    {
        for (int i = 0; i < text.Length; i += length)
        {
            yield return text.Substring(i, Math.Min(length, text.Length - i));  
        }
    }
    

提交回复
热议问题