C#:拆分字符串而不返回空字符串 [英] C#: splitting a string and not returning empty string

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

问题描述

我有一个字符串:

a = "1;2;3;"

我想以这种方式split:

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

如何确保只返回 123 而不是空字符串"?

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

如果我拆分 1;2;3 那么我会得到我想要的.但是如果我拆分 1;2;3; 那么我会得到一个额外的空字符串".我已经采纳了建议并做到了这一点:

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:

错误 1 ​​'string.Split(params) 的最佳重载方法匹配char[])' 有一些无效的参数 C:Documents 和设置agordon我的文档Visual Studio2008ProjectslomdbEnterDataDataEntryDAL.cs 18 36 EnterData

Error 1 The best overloaded method match for 'string.Split(params char[])' has some invalid arguments C:Documents and SettingsagordonMy DocumentsVisual Studio 2008ProjectslomdbEnterDataDataEntryDAL.cs 18 36 EnterData

错误 2 参数2":无法从System.StringSplitOptions"转换'char' C:Documents and SettingsagordonMy DocumentsVisual Studio2008ProjectslomdbEnterDataDataEntryDAL.cs 18 68 EnterData

Error 2 Argument '2': cannot convert from 'System.StringSplitOptions' to 'char' C:Documents and SettingsagordonMy DocumentsVisual Studio 2008ProjectslomdbEnterDataDataEntryDAL.cs 18 68 EnterData

推荐答案

String.Split 在包含任何 StringSplitOptions 时采用 array :

String.Split takes an array when including any StringSplitOptions:

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

如果您不需要选项,则语法会变得更简单:

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

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

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

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