cannot convert from 'string' to 'char[]' for split

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I am using the following code to split a string:

string sss="125asdasdlkmlkdfknkldj125kdjfngdkjfndkg125ksndkfjdks125";  List s = new List(sss.Split("125")); 

However, I receive a compile time error:

cannot convert from 'string' to 'char[]'

What is the correct way to split a string by another string?

回答1:

There is no overload for String.Split which takes just a string, instead use the next closest match:

List s = new List(     sss.Split(new string[] { "125" }, StringSplitOptions.None); 


回答2:

You can just create a char []:

 List s = new List(sss.split(new char[] {'1', '2', '5'})) 

or

 List s = new List(sss.split("125".ToCharArray())); 

More information: http://msdn.microsoft.com/en-us/library/ezftk57x.aspx



回答3:

That depends on what you wish to achieve. If you wish to split at the string "125" then do

sss.split(new[]{"125"},StringSplitOptions.RemoveEmptyEntries); //or StringSplitOptions.None 

if you wish to split at any occurrence of 1, 2 or 5 then do

sss.split(new[]{'1','2','5'});  


回答4:

Use a string array:

sss.Split(new[]{"125"},StringSplitOptions.None) 

Or StringSplitOptions.RemoveEmptyEntries if you don't want a blank string for before the first 125.



回答5:

Try this:

//string = "friend&mom&dad&brother"   string.Split('&')[int]; //string.Split('&')[0] = "friend"
//string.Split('&')[1] = "mom"
//string.Split('&')[2] = "dad"
//string.Split('&')[3] = "brother"


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!