Confusing error when splitting a string

2019-01-15 10:55发布

问题:

I have this line of code:

string[] ids = Request.Params["service"].Split(",");

the values in Request.Params["service"] are: "1,2"

Why am I getting:

Error   1   The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Error   2   Argument 1: cannot convert from 'string' to 'char[]'

This makes no sense to me....

The error happens on everything to the right of the equal sign

回答1:

You need to pass a character (System.Char), not a string:

string[] ids = Request.Params["service"].Split(',');

There is no overload to String.Split that takes a params string[] or a single string, which is what would be required to make your code work.

If you wanted to split with a string (or multiple strings), you would need to use a string[] and specify splitting options:

string[] ids = Request.Params["service"].Split(new[]{","}, StringSplitOptions.None);


回答2:

You have to use the overload with the params Char[]:

string[] ids = Request.Params["service"].Split(',');


回答3:

As others said on here your provided (",") the double quote denotes a string and the Split function accepts a Character array or char[]. Use (',') , the single quote denotes a character. You can also pass along StringSplitOptions which if you happen to get empty values in your string[] it requires a char[] to be passed along with it, illustrated below.

        string splitMe = "test1,test2,";
        string[] splitted1 = splitMe.Split(',');
        string[] splitted2 = splitMe.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
        //Will be length 3 due to extra comma
        MessageBox.Show(splitted1.Length.ToString());
        //Will be length 2, Removed the empty entry since there was nothing after the comma
        MessageBox.Show(splitted2.Length.ToString());


回答4:

In the line Request.Params["service"].Split(",");

You're splitting by "," instead of ','

The .Split() method takes an array of characters, not a string