Splitting a String in C#

When I was at university programming in C, I spent a lot of time writing command line (shell based) programs. In doing so, one of the things you might need to do is parse the command line and split them it into various options (i.e. a.out –cd –sstring would often generate an array of –c, –d and –sstring.).

There was a library to do that of course (getopt), but I sometimes enjoyed writing my own, figuring I would learn more that way.

Anyway, thinking back to that and a recently read challenge on Daily Programmer, I wondered how you could partially achieve that in C# and the excellent built in class libraries.

That led me to:

The Split method takes a character array of delimiters, and returns an array of strings. This works perfectly on strings like:

But falls down when you have sentences (strings) like this:

The reason for that is because Split, in the form above, will create an empty string array element between each pair of delimiters (in this case, spaces). What do I mean? You basically end up with:

and so on.

To fix this, Split does take a second parameter (StringSplitOptions) which is an enumerated type that contains the element: RemoveEmptyEntries. Adding that in, we reach a final solution of:

That’s pretty easy,  but what if you wanted to roll your own?

Here is my solution which doesn’t cater for multiple delimiters, nor is it overly careful about inputs. It’s merely a simple attempt at replicating the functionality in C#. Hope it’s useful.



Written by Stephen Moon
email: stephen at logicalmoon.com
www: https://www.logicalmoon.com

Hey! Did you enjoy reading this? If you did and would like an email when I add new content, just subscribe to my list. You can unsubscribe at any time.

This entry was posted in: c#. Bookmark the ➜ permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *