im in ur web, enriching ur code

 
 

February 2007 Entries

Text Helper Utility Part 2: Separation of cased words

Following yesterday's TextHelper.Coalesce post, I'd like to share another useful method for separating cased words i.e. PascalCase or camelCase.

There are a few reasons you might want to do this. It's common place today to use it in Javascript for dealing to CSS styles and the like. The inspiration behind this one was to be able to display the members of an enumeration in a meaningful way to the user e.g. using Enum.GetNames to bind possible values to a drop down list.

Consider the following enumeration:

public enum MyEnum
{
    Pending,
    Active,
    SaveForLater
}

When using Enum.GetNames( typeof( MyEnum ) ), the first two members are great, but the last member, SaveForLater, just doesn't look right when it comes to UI.

The following code would yield the string "Save For Later".

TextHelper.Separate( MyEnum.SaveForLater.ToString() );

Enter TextHelper.Separate().

This method searches a given string prefixing a separator string when it finds an uppercase character. It also considers two uppercase characters in a row as an acronym and only appends the separator when the preceding character is lowercase.

To create the separate method, I compared a version done with regular expressions to the implementation below, which the non-regex version out-performed the regex by a factor of 11. So here's the code, again its simple, but extremely helpful when you need it.

public static class TextHelper
{
    public static string Separate( string casedWord, string separator )
    {
        StringBuilder result = new StringBuilder();
        for( int i = 0, length = casedWord.Length; i < length; i++ )
        {
            if( i > 0 && i < length - 1 
                && char.IsUpper( casedWord[ i ] ) 
                && !char.IsUpper( casedWord[ i - 1 ] ) )
            {
                result.Append( separator );
            }
            result.Append( casedWord[ i ] );
        }
        return result.ToString();
    }
 
    public static string Separate( string casedWord )
    {
        return Seperate( casedWord, " " );
    }
 
    public static string Hyphenate( string casedWord )
    {
        return Separate( casedWord, "-" );
    }
 
    public static string ApplySpaces( string casedWord )
    {
        return Separate( casedWord, " " );
    }
}

You'll also notice the convenience Hyphenate method which is there for your, erm, convenience :)

kick it on DotNetKicks.com

posted @ Wednesday, February 28, 2007 8:46 AM | Feedback (1)
Filed Under [ C#, TextHelper, Utilities, Tips, .NET, Source Code ]

Text Helper Utility Part 1: C# Coalesce

I thought that I should start with something simple, yet useful, to get the blogging juices flowing. So I'm going to write about some of the utility and helper classes I deal with on a day to day basis; The TextHelper.

TextHelper is static helper class containing useful methods for dealing with text and strings.

Existing language functionality:

The first method, and the one I use the most, is a spin off of the Transact-SQL COALESCE function. It adheres to the same principle as the SQL version in that it takes a variable number of arguments, and returns the first non-null, and in our case non-empty, argument. The T-SQL version is used along the lines of:

COALESCE( [Col0], [Col1], 'None' )

Since C# 2.0, we've also had the coalesce operator; a very handy operator, which can save a lot of if ... else statements. It is used to return the first object that is not null like so:

MyObject a = null;
MyObject
b = new MyObject();
MyObject c = a ?? b;

In the example above, b is the first non-null argument, and is assigned to the variable c.

Why another Coalesce method?

The difference between the aforementioned two methods and the TextHelper.Coalesce method is that they only deal with null values, but we often want null and empty to be considered the same when dealing with User Interfaces. Consider the following example of getting a contact number to display.

string phone = TextHelper.Coalesce( customer.Phone, customer.Mobile, "None Avaialble" );

Now when the customer has a empty phone number, the mobile number is returned, and if no mobile number is specified, "None Available" is used as an indicator.

Source Code:

Here's the code extract from the text helper class.

public static class TextHelper
{
    public static string Coalesce( params string[] args )
    {
        string value = string.Empty;
        foreach( string arg in args )
        {
            if( !string.IsNullOrEmpty( arg ) )
            {
                value = arg;
                break;
            }
        }
        return value;
    }
}

It's an extremely simple method and simply helps cut down on writing more lines of code than are necessary.

It also makes dealing with configuration "AppSetting" a little simpler too e.g.

string setting = TextHelper.Coalesce( ConfigurationManager.AppSettings[ "MyAppSettingKey" ], "My Default Value" );

What's Next?

Next time I'll be adding another simple method from the TextHelper class that separates cased words. Handy for displaying PascalCased enum strings and the like.

kick it on DotNetKicks.com

posted @ Tuesday, February 27, 2007 8:20 AM | Feedback (1)
Filed Under [ C#, TextHelper, Utilities, Tips, .NET, Source Code ]

Recently on C# Vitamins...

Powered By Subtext

 

About C# Vitamins

Dave has been working in the industry for around 14 years, and has a focus on Javascript, C#, ASP.NET and SQL Server web development; not to mention being a standards driven type of guy.

C# Vitamins is the result of his findings while working in the web industry and a desire to share with the community; and if it was traced back far enough, you might say it might not have existed if he hadn't taken such an interest in id Software's original Quake.

Related Links

Below is a list of related links of Dave's other sites.