Why isn't there a string.Split(string) overload? [closed]

不羁岁月 提交于 2019-12-01 03:38:59

Tweaking the question to be "Why is the StringSplitOptions parameter compulsory when calling String.Split() with a String[] argument?" might provide an answer to your question.

Note that there's not actually a String.Split() overload which accepts a single character. The overload takes a Char[] but as it's a params array you can call it with a single character and it is implicitly cast to a Char[]. e.g.

"1,2,3,4,5".Split(',');

calls the same Split() overload as

"1,2,3,4,5".Split(new[] { ',' });

If there were an overload of Split() which accepted a single argument of String[] then you would be able to call Split by passing a single string argument.

However that overload doesn't exist and StringSplitOptions is compulsory when passing a String[] to Split. As to why StringSplitOptions is compulsory, I can only theorize but it may be that when splitting with a string, the likelihood of a complex split for the algorithm to deal with increases significantly. To provide expected results for these cases, it is preferable for the behaviour of the method, when finding multiple delimiters next to each other, to be defined. i.e. StringSplitOptions is compulsory.

You might argue that you could have a Split(String, StringSplitOptions) overload, but as Ilya Ivanov mentioned in the answer above, you need to stop somewhere and there is a perfectly good way of passing a single string in.

string input = "This - is - an - example";
string[] splitted = Regex.Split(input," - ");
foreach (string word in splitted)
{
    MessageBox.Show(word);
}

it's not only the matter of spaces, it exatcly matches your string seperator, look

string input = "This,- is,- a,- complicated,- example";
string[] splitted = Regex.Split(input,",- ");
foreach (string word in splitted)
{
    MessageBox.Show(word);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!