Home > c# > StringUtil class – Space Before a Capital Letter

StringUtil class – Space Before a Capital Letter

Hi,

I often use enumerations in code that I want to display as text on the screen. For example the state of an object recorded in an enum like

public enum StageType
{
PreRelease = 0,
Proposed = 1,
Open = 2,
Closed = 3
}

So if I get the matching value out of the database and I want to render a textual representation of the enum to the UI I migth do:

lblStatus.Text = ((StageType) iStage).ToString(); // where iStage is an int value representing the enum.

So this is great appart from the first item PreRelease will be shown without a space.

Step in my amazing class which will parse the string and add a space before a capital so “PreRelease” becomes “Pre Release”
This way I can use any Camel case enum string and have it render to the UI nicely.


public static class StringUtil
{

///
/// Returns a string with a space after a capital
///
///
///
public static string SpaceOnCapital(string word)
{
StringBuilder sb = new StringBuilder();

foreach (char c in word)
{
if (sb.Length == 0)
{
sb.Append(c);
}
else
{
// not the first character
// ch
if (IsCapital(c))
{
sb.AppendFormat(” {0}”, c);
}
else
{
sb.Append(c);
}
}
}

return sb.ToString();

}

public static bool IsCapital(char c)
{
int ascii = (int)c;
return (ascii >= 65 && ascii <= 90);
}
}

Cheers

Advertisements
Categories: c#
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: