你将如何从数组中删除空白条目

Rod*_*Rod 8 c#

你如何从阵列中删除空白项目?

迭代并将非空白项目分配给新数组?

String test = "John, Jane";

//Without using the test.Replace(" ", "");

String[] toList = test.Split(',', ' ', ';');
Run Code Online (Sandbox Code Playgroud)

Tim*_*oyd 26

使用过载string.Split需要StringSplitOptions:

String[] toList = test.Split(new []{',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)

  • 得爱SO - 从来不知道`StringSplitOptions.RemoveEmptyEntries` :) (2认同)

Jon*_*eet 5

您将使用其重载string.Split允许抑制空项:

String test = "John, Jane";
String[] toList = test.Split(new char[] { ',', ' ', ';' }, 
                             StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,每次都不会创建新数组:

 private static readonly char[] Delimiters = { ',', ' ', ';' };
 // Alternatively, if you find it more readable...
 // private static readonly char[] Delimiters = ", ;".ToCharArray();

 ...

 String[] toList = test.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)

Split 不修改列表,所以应该没问题.