简体   繁体   中英

Split a string based on white space in C#

I have a string "dexter is good annd bad".

I want create a list by splitting this string based on the space.

I have achieved this using following code

string ss = "dexter is  good    annd        bad";
    var s = !string.IsNullOrEmpty(ss) && ss!= "null"? ss.Split(' ').ToList(): new List<string>();

The problem is this list also contains spaces, I don't need spaces or empty string to be in my list.

您可以使用String.Split方法:

var s = ss.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

Another option is to use the Regex.Split Method from System.Text.RegularExpressions:

string[] s = Regex.Split(ss, @"\s+");

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