How to split a string while preserving line endings?

后端 未结 6 1273
谎友^
谎友^ 2021-01-01 06:02

I have a block of text and I want to get its lines without losing the \\r and \\n at the end. Right now, I have the following (suboptimal code):

<         


        
6条回答
  •  余生分开走
    2021-01-01 06:37

    You can achieve this with a regular expression. Here's an extension method with it:

        public static string[] SplitAndKeepDelimiter(this string input, string delimiter)
        {
            MatchCollection matches = Regex.Matches(input, @"[^" + delimiter + "]+(" + delimiter + "|$)", RegexOptions.Multiline);
            string[] result = new string[matches.Count];
            for (int i = 0; i < matches.Count ; i++)
            {
                result[i] = matches[i].Value;
            }
            return result;
        }
    

    I'm not sure if this is a better solution. Yours is very compact and simple.

提交回复
热议问题