C#中如何排除过滤清空删除掉字符串数组中的空字符串⽅式⼀:使⽤lambda表达式筛选过滤掉数组中空字符串
/// <summary>
/// 使⽤lambda表达式排除/过滤/清空/删除掉字符串数组中的空字符串
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string[] strArray = { "","111","","222","","333"};
Console.WriteLine("输出带有空字符串的数组:");
foreach (string str in strArray)
{
Console.WriteLine(str);
}
Console.WriteLine("-------------------------------------------");
//使⽤lambda表达式过滤掉空字符串
strArray = strArray.Where(s=>!string.IsNullOrEmpty(s)).ToArray();
Console.WriteLine("输出过滤掉空字符串的数组:");
foreach (string str in strArray)
{
Console.WriteLine(str);
}
Console.Read();
}
⽅式⼆:使⽤泛型集合List<string>的ForEach循环,过滤获取正确的字符串,重新添加到新字符串数组中
string[] strArray = { "", "111", "", "222", "", "333" };
Console.WriteLine("输出带有空字符串的数组:");
foreach (string str in strArray)
{
Console.WriteLine(str);
}
Console.WriteLine("-------------------------------------------");
/*
*使⽤List泛型集合的ForEach⽅法循环获取⾮空空字符串
*这⾥使⽤了匿名⽅法
*/
List<string> list = new List<string>();
strArray.ToList().ForEach(
(s) =>
{
if (!string.IsNullOrEmpty(s))
{
list.Add(s);
}
}
)
;
strArray = list.ToArray();
Console.WriteLine("输出过滤掉空字符串的数组:");
foreach (string str in strArray)
{
Console.WriteLine(str);
}
Console.Read();
⽅式三:使⽤传统循环⽅式来排除和删除字符串数组中的空字符串
string[] strArray = { "", "111", "", "222", "", "333" };
Console.WriteLine("输出带有空字符串的数组:");
foreach (string str in strArray)
{
Console.WriteLine(str);
}
Console.WriteLine("-------------------------------------------");
//使⽤循环排除和过滤掉空字符串
List<string> list = new List<string>();
foreach (string s in strArray)
字符串转数组去除空格{
if (!string.IsNullOrEmpty(s))
{
list.Add(s);
}
}
strArray = list.ToArray();
Console.WriteLine("输出过滤掉空字符串的数组:"); foreach (string str in strArray)
{
Console.WriteLine(str);
}
Console.Read();
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论