Easiest way to split a string on newlines in .NET?

后端 未结 16 2322
抹茶落季
抹茶落季 2020-11-22 06:57

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a ne

16条回答
  •  长情又很酷
    2020-11-22 07:29

    I just thought I would add my two-bits, because the other solutions on this question do not fall into the reusable code classification and are not convenient.

    The following block of code extends the string object so that it is available as a natural method when working with strings.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Collections;
    using System.Collections.ObjectModel;
    
    namespace System
    {
        public static class StringExtensions
        {
            public static string[] Split(this string s, string delimiter, StringSplitOptions options = StringSplitOptions.None)
            {
                return s.Split(new string[] { delimiter }, options);
            }
        }
    }
    

    You can now use the .Split() function from any string as follows:

    string[] result;
    
    // Pass a string, and the delimiter
    result = string.Split("My simple string", " ");
    
    // Split an existing string by delimiter only
    string foo = "my - string - i - want - split";
    result = foo.Split("-");
    
    // You can even pass the split options parameter. When omitted it is
    // set to StringSplitOptions.None
    result = foo.Split("-", StringSplitOptions.RemoveEmptyEntries);
    

    To split on a newline character, simply pass "\n" or "\r\n" as the delimiter parameter.

    Comment: It would be nice if Microsoft implemented this overload.

提交回复
热议问题