简体   繁体   中英

String.Split() method: compiler chooses wrong overload

I have the following code:

using System;

class Token
{
    static void Main()
    {
        Console.Write("Enter string to tokenize: ");
        string s = Console.ReadLine();
        Console.WriteLine("\nString length: {0}\n\nTokens:", s.Length);
        string[] tok = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); //<-- this line causes CS1503
        //string[] tok = s.Split(); //works but also returns empty entries
        foreach (string i in tok)
            Console.WriteLine("{0}", i);
        Console.Write("\n{0} tokens found\nPress any key to continue . . . ", tok.Length);
        Console.ReadKey();
    }
}

The code is supposed to take a string from the console input and split it into tokens (separated by spaces). I am using the String.Split() method. By default, this method returns all the empty tokens (if there are multiple consecutive separators), which is something I don't want. According to MSDN this method has a bunch of overloads. The default String.Split() with no parameters calls this overload:

public string[] Split(params char[] separator);

There is an overload which doesn't return the empty tokens:

public string[] Split(char separator, StringSplitOptions options = System.StringSplitOptions.None);

From what I understand, in order to make it not return empty tokens, the second parameter has to be StringSplitOptions.RemoveEmptyEntries . So the intuitive way to call this is:

s.Split(' ', StringSplitOptions.RemoveEmptyEntries);

The compiler, however, thinks otherwise, and throws error CS1503 at me:

CS1503: Argument 2: cannot convert from 'System.StringSplitOptions' to 'char'

So it's obvious that the compiler is not choosing the overload I want. Hovering over the function calls makes IntelliSense show me this:

string[] Split(params char[] separator)

How should I call String.Split() in order to call the overload I want?

In .NET Framework use

char[] charSeparators = new char[] { ' ' };
string[] tok = s.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);

In NET core (I test in 2.2). the code is working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM