How to split a string while preserving line endings?

后端 未结 6 1263
谎友^
谎友^ 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:39

    As always, extension method goodies :)

    public static class StringExtensions
    {
        public static IEnumerable SplitAndKeep(this string s, string seperator)
        {
            string[] obj = s.Split(new string[] { seperator }, StringSplitOptions.None);
    
            for (int i = 0; i < obj.Length; i++)
            {
                string result = i == obj.Length - 1 ? obj[i] : obj[i] + seperator;
                yield return result;
            }
        }
    }
    

    usage:

            string text = "One,Two,Three,Four";
            foreach (var s in text.SplitAndKeep(","))
            {
                Console.WriteLine(s);
            }
    

    Output:

    One,

    Two,

    Three,

    Four

提交回复
热议问题