Created
July 31, 2022 20:41
-
-
Save bestknighter/b588922f1c8a7b5966295c14c4237dbe to your computer and use it in GitHub Desktop.
C# String Extensions
This file contains hidden or 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
public static class StringExtensions { | |
/// <summary> | |
/// Transforms strings like variable and class names to nice UI-friendly strings, removing | |
/// underlines, hiphens, prefixes and the like | |
/// </summary> | |
/// <param name="str">The string to be nicified</param> | |
/// <param name="preserveAccronyms">If accronym letters should be kept together</param> | |
/// <returns>A nicified Title Cased version ready for UIs</returns> | |
public static string Nicify(this string str, bool preserveAccronyms = true) { | |
string trimmed = str; | |
if( trimmed[1] == '_' ) trimmed = trimmed.Remove(0, 2); | |
if( trimmed[0] == '_' ) trimmed = trimmed.Remove(0, 1); | |
if( trimmed[0].IsLowerCase() && trimmed[1].IsUpperCase() ) trimmed = trimmed.Remove(0, 1); | |
string[] strs = trimmed.Split('_', '-'); | |
if( strs.Length == 1 ) { | |
string nicified = ""; | |
for( int i = 0; i < trimmed.Length; i++ ) { | |
if(i == 0) nicified += trimmed[i].ToUpper(); | |
else if(trimmed[i].IsUpperCase()) { | |
bool shouldAddSpace = !(preserveAccronyms && trimmed[i-1].IsUpperCase()); | |
shouldAddSpace |= i < trimmed.Length-2 && trimmed[i+1].IsLowerCase(); | |
nicified += (shouldAddSpace ? " " : "") + trimmed[i]; | |
} else nicified += trimmed[i]; | |
} | |
return nicified; | |
} else { | |
string nicified = ""; | |
foreach( string s in strs ) { | |
nicified += " "+s.Nicify(); | |
} | |
return nicified.Remove(0, 1); | |
} | |
} | |
/// <returns>Checks if a character is a lowercase letter</returns> | |
public static bool IsLowerCase(this char c) { | |
return (c >= 'a' && c <= 'z') || (c >= 'à' && c <= 'ý'); | |
} | |
/// <returns>Checks if a character is an UPPERCASE letter</returns> | |
public static bool IsUpperCase(this char c) { | |
return (c >= 'A' && c <= 'Z') || (c >= 'À' && c <= 'Ý'); | |
} | |
/// <returns>Checks if a character is a letter</returns> | |
public static bool IsLetter(this char c) { | |
return c.IsLowerCase() || c.IsUpperCase(); | |
} | |
/// <returns>Transforms a letter to UPPERCASE</returns> | |
public static char ToUpper(this char c) { | |
if( c.IsLowerCase() ) return (char)(c-32); | |
else return c; | |
} | |
/// <returns>Transforms a letter to lowercase</returns> | |
public static char ToLower(this char c) { | |
if( c.IsUpperCase() ) return (char)(c+32); | |
else return c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment