You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将数组中的空字符串替换为"-"?求便捷实现方法

How to Replace Empty Strings in a Split Array with "-"

Hey there! I see you're working with splitting a string and replacing empty entries with "-"—let's break down how to do this properly, including a clean, shorthand method.

First, a quick note: your original Split code has a small syntax issue. The correct way to split the string and retain empty entries is:

string data = "a,bn,,rf,,";
// This gives you the array {"a", "bn", "", "", "rf", "", ""} as expected
string[] dataArray = data.Split(',');

The second parameter in your code was incorrect—Split doesn't take the original string as a second argument here. Using Split(',') (or explicitly Split(',', StringSplitOptions.None)) keeps all empty segments from the commas.

Method 1: Manual Loop Replacement

If you prefer a straightforward, no-LINQ approach, you can iterate over the array and replace empty strings directly:

for (int i = 0; i < dataArray.Length; i++)
{
    // Check if the element is empty (or null, though Split won't produce null here)
    if (string.IsNullOrEmpty(dataArray[i]))
    {
        dataArray[i] = "-";
    }
}
// Result: {"a", "bn", "-", "-", "rf", "-", "-"}

For a more elegant one-liner, use LINQ's Select method to transform each element. This is the most convenient way to handle this:

// Don't forget to add this using directive at the top of your file
using System.Linq;

string[] replacedArray = dataArray
    .Select(s => string.IsNullOrEmpty(s) ? "-" : s)
    .ToArray();

This works by:

  • Iterating over every element in dataArray with Select
  • Using a ternary operator to replace empty strings with "-", while keeping non-empty values as-is
  • Converting the resulting IEnumerable back to an array with ToArray()

You can even combine the split and replacement into a single line for brevity:

string[] replacedArray = data.Split(',').Select(s => string.IsNullOrEmpty(s) ? "-" : s).ToArray();

Edge Case Handling

If you also need to handle whitespace-only strings (like " "), replace string.IsNullOrEmpty with string.IsNullOrWhiteSpace to catch those too.


内容的提问来源于stack exchange,提问作者cm.goh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:07:33