Oct
03
2006
ProperCase function in C#
Posted by admin under
.NET
I've seen a lot of variants of this function, while being really simple it allows for a lot of different solutions.
For example, solutions with regular expressions are quite popular floating around the web but the solution I use is so simple:
public static string ProperCase(string stringInput)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
bool fEmptyBefore = true;
foreach (char ch in stringInput)
{
char chThis = ch;
if (Char.IsWhiteSpace(chThis))
fEmptyBefore = true;
else
{
if (Char.IsLetter(chThis) && fEmptyBefore)
chThis = Char.ToUpper(chThis);
else
chThis = Char.ToLower(chThis);
fEmptyBefore = false;
}
sb.Append(chThis);
}
return sb.ToString();
}
it will turn all these cases:
string s1 = ProperCase("STefan HOLMBERG"); s1 = ProperCase("stefan holmberg"); s1 = ProperCase("steFan holmberg");
into Stefan Holmberg
While this solution
string sName = Microsoft.VisualBasic.Strings.StrConv("stefan holmberg sweden . You bet. this is a cool function",
Microsoft.VisualBasic.Constants.vbProperCase,0);
-e using the VisualBasic runtime functions from within C# is possible - and also quite nice - you need to remember to add a reference to Microsoft.VisualBasic.dll in order to use it