4

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
ISHIDA
  • 4,700
  • 2
  • 16
  • 30
  • This is duplicate question, and offered answers are not optimal. See https://stackoverflow.com/questions/6111298/best-way-to-specify-whitespace-in-a-string-split-operation – ivo.tisljar Apr 08 '23 at 20:31

2 Answers2

13

You can use String.Split method:

var s = ss.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Darjan Bogdan
  • 3,780
  • 1
  • 22
  • 31
1

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

string[] s = Regex.Split(ss, @"\s+");
nwsmith
  • 475
  • 4
  • 8