The String.Split
method, when used with whitespace as the delimiter, often requires defining a character array containing spaces and tabs. This can be repetitive and error-prone. Two simpler alternatives exist:
1. Using a null
or Empty Separator:
<code class="language-csharp">string[] ssize = myStr.Split(null); // Or: myStr.Split();</code>
Passing null
or omitting the separator argument tells String.Split
to use whitespace characters (as defined by Char.IsWhiteSpace
) as delimiters.
2. Zero-Length Character Array:
<code class="language-csharp">string[] ssize = myStr.Split(new char[0]);</code>
Creating an empty character array achieves the same result: whitespace-based splitting.
Both methods are supported by the String.Split(char[])
documentation, which explicitly states that a null
or empty separator array implies whitespace delimiters. This approach significantly simplifies code, reducing redundancy and the risk of errors associated with manually defining character arrays for whitespace.
The above is the detailed content of How Can I Simplify String.Split Whitespace Handling in C#?. For more information, please follow other related articles on the PHP Chinese website!