10

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?

JSteh
  • 165
  • 1
  • 8
  • 1
    For flags to work the values have to increase in powers of 2. [The flags attribute has some documentation](https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=net-6.0) – Crowcoder Jul 12 '22 at 20:57
  • That makes more sense now. Bitwise OR would always give a unique value if the operands are just bit-shifted ones. – JSteh Jul 12 '22 at 21:02

1 Answers1

25

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);  
Sergey Sosunov
  • 4,124
  • 2
  • 11
  • 15
  • Additional clarifications: https://stackoverflow.com/a/8480/5767872 – Sergey Sosunov Jul 12 '22 at 20:57
  • Thank you that works perfectly! I assumed the bitwise OR of two enum values would be the bitwise OR of their numeric values, but I'm apparently off base. I'll read up on the [Flags] attribute and enums. Thanks again! – JSteh Jul 12 '22 at 20:58
  • 3
    @JSteh No, you're not off base, the bitwise OR of two enum values are exactly the bitwise OR of their numeric values, you're 100% correct in this regard. – Lasse V. Karlsen Jul 12 '22 at 22:10