I would like to split a string by a delimiter ";" and apply both StringSplitOptions.TrimEntries
and StringSplitOptions.RemoveEmptyEntries
. I tried using an array of StringSplitOptions like
// myString already defined elsewhere
StringSplitOptions[] options = { StringSplitOptions.TrimEntries, StringSplitOptions.RemoveEmptyEntries };
string[] strs = myString.Split(';', options);
but this doesn't compile. I know I can remove whitespaces later with Trim(), but would prefer a clean single-statement solution and it seems like you should be able to use multiple (both) options. In the page for the StringSplitOptions enum , it mentions
If RemoveEmptyEntries and TrimEntries are specified together, then substrings that consist only of white-space characters are also removed from the result.
Neither the rest of the page nor the page for the String.Split() method give any indication of how they could be specified together.
I may be missing something simple since I'm fairly new to and self-taught in C#. Excuse me if this post is formatted poorly or is a duplicate question, first post on Stack Overflow. I tried searching for this issue and didn't see any results. Thanks in advance for any guidance you can give?
CodePudding user response:
StringSplitOptions enum is marked with [Flags] attribute, and you can combine multiple Flags by |
operator.
using System;
public class Program
{
public static void Main()
{
var myString = " ; some test ; here; for; test ; ; ;";
string[] strs = myString.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
foreach (var str in strs)
{
Console.WriteLine($"-{str}-");
}
}
}
Output:
-some test-
-here-
-for-
-test-
Or
StringSplitOptions splitOptions = StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries;
string[] strs = myString.Split(';', splitOptions);