Skip to content

Instantly share code, notes, and snippets.

@mqudsi
Created April 25, 2012 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mqudsi/2485796 to your computer and use it in GitHub Desktop.
Save mqudsi/2485796 to your computer and use it in GitHub Desktop.
Function for correcting capitalization of user-entered names
namespace NeoSmart
{
public static class Utils
{
//This function will only attempt to capitalize the first letter, etc. of a name
//if and only if the user appears to have entered all caps or all lowercase
public static string ProperCase(string stringToFormat)
{
System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
//Check if we have a string to format
if (String.IsNullOrEmpty(stringToFormat))
{
//Return an empty string
return string.Empty;
}
//Check if string already contains both upper and lower, in which case assume it's correct
bool hasLower = false;
bool hasUpper = false;
foreach (char c in stringToFormat)
{
if (!Char.IsLetter(c))
continue;
if (Char.IsUpper(c))
hasUpper = true;
else
hasLower = true;
if (hasUpper && hasLower)
return stringToFormat;
}
//From http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx:
//"However, this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym."
return textInfo.ToTitleCase(stringToFormat.ToLower());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment