What are the alternatives to Split a string in c# that don't use String.Split()

前端 未结 3 2078
谎友^
谎友^ 2021-01-07 05:39

I saw this question that asks given a string \"smith;rodgers;McCalne\" how can you produce a collection. The answer to this was to use String.Split.

If we don\'t ha

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-07 06:10

    It's reasonably simple to write your own Split equivalent.

    Here's a quick example, although in reality you'd probably want to create some overloads for more flexibility. (Well, in reality you'd just use the framework's built-in Split methods!)

    string foo = "smith;rodgers;McCalne";
    foreach (string bar in foo.Split2(";"))
    {
        Console.WriteLine(bar);
    }
    
    // ...
    
    public static class StringExtensions
    {
        public static IEnumerable Split2(this string source, string delim)
        {
            // argument null checking etc omitted for brevity
    
            int oldIndex = 0, newIndex;
            while ((newIndex = source.IndexOf(delim, oldIndex)) != -1)
            {
                yield return source.Substring(oldIndex, newIndex - oldIndex);
                oldIndex = newIndex + delim.Length;
            }
            yield return source.Substring(oldIndex);
        }
    }
    

提交回复
热议问题