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
[csharp]
public enum StageType
{
PreRelease = 0,
Proposed = 1,
Open = 2,
Closed = 3
}
[/csharp]
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 might do:
lblStatus.Text = ((StageType) iStage).ToString(); // where iStage is an int value representing the enum.
So this is great apart 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.
[csharp]
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);
}
}
[/csharp]
Cheers