摆脱 C# 数组中的空/空字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/635751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting rid of null/empty string values in a C# array
提问by zohair
I have a program where an array gets its data using string.Split(char[] delimiter). (using ';' as delimiter.)
我有一个程序,其中数组使用 string.Split(char[] 分隔符) 获取其数据。(使用“;”作为分隔符。)
Some of the values, though, are null. I.e. the string has parts where there is no data so it does something like this:
但是,有些值是 null。即字符串有没有数据的部分,所以它做这样的事情:
1 ;2 ; ; 3;
1 ;2 ; ; 3;
This leads to my array having null values.
这导致我的数组具有空值。
How do I get rid of them?
我该如何摆脱它们?
采纳答案by Tamas Czinege
Try this:
尝试这个:
yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
回答by sgriffinusa
You could use the Where linq extension method to only return the non-null or empty values.
您可以使用 Where linq 扩展方法仅返回非空值或空值。
string someString = "1;2;;3;";
IEnumerable<string> myResults = someString.Split(';').Where<string>(s => !string.IsNullOrEmpty(s));
回答by Blessed Geek
You should replace multiple adjacent semicolons with one semicolon before splitting the data.
在拆分数据之前,您应该用一个分号替换多个相邻的分号。
This would replace two semicolons with one semicolon:
这将用一个分号替换两个分号:
datastr = datastr.replace(";;",";");
But, if you have more than two semicolons together, regex would be better.
但是,如果你有两个以上的分号,正则表达式会更好。
datastr = Regex.Replace(datastr, "([;][;]+)", ";");
回答by Sameer Shaikh
public static string[] nullLessArray(string[] src)
{
Array.Sort(src);
Array.Reverse(src);
int index = Array.IndexOf(src, null);
string[] outputArray = new string[index];
for (int counter = 0; counter < index; counter++)
{
outputArray[counter] = src[counter];
}
return outputArray;
}
回答by bjoiuzt
words = poly[a].Split(charseparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
{
richTextBox1.Text += (d + 1)+ " " + word.Trim(',')+ "\r\n";
d++;
}
charseparators is a space
字符分隔符是一个空格