2011-10-21 52 views
5

我有,我进入输入作为分割字符串,空的空间也被认为是字符串如何丢弃空字符串

"Two; [email protected];" 

string[] result = txt_to.Text.Split(';'); 

所以这里所发生的是结果需要三根弦文本框。 1. two 2. [email protected] 3.“”(空白空间),因为有一个;在电子邮件之后,它认为这是一个字符串,我怎样才能丢弃它所需要的第三个字符串。当我输入电子邮件和分号并按空格键时会发生错误。如果它是分号后的空格,分割应该放弃它该怎么做

回答

12

我收集你想要将字符串拆分为多个字符串,但排除任何“空”字符串(只包含空格)? This应该帮助你...

string[] result = txt_to.Text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); 
6
var arr = mystring.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries); 
+0

+1将工作:-) – xanatos

+0

是否RemoveEmptyEntries也删除空间?我认为这只是删除String.Empty ...虽然没有测试过。 –

3

StringSplitOptions参数

var result = yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries); 
2

它看起来对我来说,放弃空字符是有意义的无论如何,不​​仅仅是最后的结果。如果是这样的话,你可以使用

char[] separators = new char[]{';'}; 
string[] result = txt_to.Text.Split(separators , StringSplitOptions.RemoveEmptyEntries); 
0
string s=txt_to.Text; 
s = s.Replace(" ", ""); 
string[] result = s.Split(';');