You need to enable JavaScript to run this app. 如何将C#字符串数组中null或空值的索引位置替换为新字符串
优惠活动
大模型
产品
解决方案
定价
更多

如何将C#字符串数组中null或空值的索引位置替换为新字符串

C# 数组空值替换实现方案
  • 核心判断逻辑使用string.IsNullOrEmpty()方法,可同时匹配null和空字符串""两种场景,符合你的需求
  • 数组遍历推荐直接用原生Length属性,比调用LINQ扩展的Count()方法性能更优
  • 匹配到符合条件的元素时,直接对当前索引位置的数组元素赋值即可完成替换

完整可运行代码

string[] namelist = new string[4] { "dodo", "klee", "diluc", null };
// 自定义替换的文本,可以根据需求自行修改
string replaceText = "custom string";

for (int i = 0; i < namelist.Length; i++)
{
    if (string.IsNullOrEmpty(namelist[i]))
    {
        // 替换null或空值
        namelist[i] = replaceText;
    }
    else
    {
        Console.WriteLine("Taken");
    }
}

// 验证修改结果的可选代码
foreach (var item in namelist)
{
    Console.WriteLine(item);
}

如果你还需要把仅由空格/制表符等空白字符组成的字符串(比如" ")也纳入替换范围,把string.IsNullOrEmpty替换为string.IsNullOrWhiteSpace即可。

内容的提问来源于stack exchange,提问作者Daniel Canaria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 20:30:01