Created
April 25, 2012 02:51
-
-
Save mqudsi/2485796 to your computer and use it in GitHub Desktop.
Function for correcting capitalization of user-entered names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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