C#:拆分字符串,并没有返回空字符串 [英] C#: splitting a string and not returning empty string

查看:530
本文介绍了C#:拆分字符串,并没有返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

  A =1; 2; 3; 

和我想拆分 IT这方式:

 的foreach(字符串b在a.split(';'))

我怎样才能确保我只返回 1 2 3 ,而不是一个'空字符串'?



如果我分裂 1; 2; 3 然后,我会得到我想要的东西。但是,如果我分裂 1; 2; 3; 然后我得到一个额外的空字符串。我已经建议,做到了这一点:

 的String [] = batchstring batch_idTextBox.Text.Split(;,StringSplitOptions.RemoveEmptyEntries ); 



不过,我得到这些错误:



< BLOCKQUOTE>

错误1为最佳重载方法匹配'string.Split(PARAMS
的char [])'有一些无效参数C:\Documents和
Settings\agordon \My Documents\Visual工作室
2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 36 EnterData



2时出错参数'2':无法从'System.StringSplitOptions'
转换为'字符'C:\Documents和Settings\agordon\My Documents\Visual工作室
2008\Projects\lomdb \EnterData\DataEntry\DAL.cs 18 68 EnterData



解决方案

String.Split需要一个阵列,包括时任 StringSplitOptions

 的String [] = batchstring batch_idTextBox.Text.Split(新的char [] {','},StringSplitOptions.RemoveEmptyEntries); 

如果您不需要的选项,语法变得更加容易:

 的String [] = batchstring batch_idTextBox.Text.Split(';'); 


I have a string:

a = "1;2;3;"

And I would like to split it this way:

foreach (string b in a.split(';'))

How can I make sure that I return only 1, 2, 3 and not an 'empty string'?

If I split 1;2;3 then I will get what I want. But if I split 1;2;3; then I get an extra 'empty string'. I have taken suggestions and done this:

string[] batchstring = batch_idTextBox.Text.Split(';', StringSplitOptions.RemoveEmptyEntries);

However, I am getting these errors:

Error 1 The best overloaded method match for 'string.Split(params char[])' has some invalid arguments C:\Documents and Settings\agordon\My Documents\Visual Studio 2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 36 EnterData

Error 2 Argument '2': cannot convert from 'System.StringSplitOptions' to 'char' C:\Documents and Settings\agordon\My Documents\Visual Studio 2008\Projects\lomdb\EnterData\DataEntry\DAL.cs 18 68 EnterData

解决方案

String.Split takes an array when including any StringSplitOptions:

string[] batchstring = batch_idTextBox.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

If you don't need options, the syntax becomes easier:

string[] batchstring = batch_idTextBox.Text.Split(';');

这篇关于C#:拆分字符串,并没有返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆