String.WordCount extension method


I’m in the final steps of a project where we needed a word count method. With some googling I found a good foundation from microsoft.com MSDN pages. I need some customizations and made an additional overrided method where I could add a string with delimiter characters, instead of char array.

    public static class MyExtension
    {
        public static int WordCount(this String str)
        {
            var splitCharts = " .?-@";
            return WordCount(str, splitCharts);
        }

        public static int WordCount(this String str, string delimiters)
        {
            var opt = StringSplitOptions.RemoveEmptyEntries;
            return str.Split(delimiters.ToArray(), opt).Length;
        }
    }

The use of the extension method is like this:

string str = "HERØY-I-MØRE-OG-ROMSDAL";
var count = str.WordCount("-");

Will result in count being 5, since delimiter is character ‘-‘.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s