2011-01-25 8 views
8

¿Cómo eliminaría el elemento en blanco de la matriz?cómo eliminaría la entrada en blanco de la matriz

¿Iterar y asignar elementos no vacíos a la nueva matriz?

String test = "John, Jane"; 

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

String[] toList = test.Split(',', ' ', ';'); 
+1

Gracias por tantas perspectivas, me encanta. – Rod

Respuesta

26

Utilice la sobrecarga de string.Split que lleva un StringSplitOptions:

String[] toList = test.Split(new []{',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries); 
+2

Tengo que amar SO - nunca he sabido de 'StringSplitOptions.RemoveEmptyEntries' :) – Oded

+0

muy bien gracias por eso – Rod

+0

@rod Me alegro de ser de ayuda. Dejaré que usted ponga en práctica el almacenamiento en caché de la matriz de delimitadores si va a llamar esto repetidamente. –

0

puede ponerlos en una lista a continuación, llamar al método toArray de la lista, o con LINQ que probablemente podría simplemente seleccionar el no en blanco y hacer para Array.

5

que usaría the overload of string.Split which allows the suppression of empty items:

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

O mejor aún, no se crearía una nueva matriz cada vez:

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); 

Split no modifica la lista, por lo que debería ser multa.

1
string[] result = toList.Where(c => c != ' ').ToArray(); 
+0

var result = toList.Where (c =>! String.IsNullOrEmpty (c)). ToArray(); – MvcCmsJon

0
string[] toList = test.Split(',', ' ', ';').Where(v => !string.IsNullOrEmpty(v.Trim())).ToArray(); 
+0

'''' todavía causará 'string.IsNullOrEmpty' para devolver falso. Si quieres usar 'IsNullOrEmpty', tendrías que' Trim() 'primero. –

+0

@Justin buen punto. pasé por alto eso: P –

1

probar esto con un poco de LINQ:

var n = Array.FindAll(test, str => str.Trim() != string.Empty); 
0

Si el separador es seguido por un espacio, que sólo puede incluirlo en el separador:

String[] toList = test.Split(
    new string[] { ", ", "; " }, 
    StringSplitOptions.None 
); 

Si el separador también se produce sin el espacio final, puede incluir también estos:

String[] toList = test.Split(
    new string[] { ", ", "; ", ",", ";" }, 
    StringSplitOptions.None 
); 

Nota: Si la cadena contiene elementos realmente vacíos, se conservarán. Es decir. "Dirk, , Arthur" no dará el mismo resultado que "Dirk, Arthur".

Cuestiones relacionadas