C#如何将数组中的空字符串替换为"-"?求便捷实现方法
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", "-", "-"}
Method 2: LINQ Shorthand (Recommended for Conciseness)
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
dataArraywithSelect - 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

