Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to use multiple StringSplitOptions in String.Split()?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading