Created
June 28, 2018 12:19
-
-
Save tkouba/d58eefcee4fb2d181f63418e698f951a to your computer and use it in GitHub Desktop.
Create valid variable name in PascalCase from any text - remove invalid characters, add underscore prefix if needed
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 string CreateName(this string s) { | |
s = s.Normalize(NormalizationForm.FormD); | |
StringBuilder sb = new StringBuilder(); | |
bool upper = true; | |
for (int i = 0; i < s.Length; i++) | |
{ | |
var cat = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(s[i]); | |
//Console.WriteLine(cat); | |
if (cat == System.Globalization.UnicodeCategory.DecimalDigitNumber && sb.Length == 0) | |
sb.Append('_'); | |
if (cat == System.Globalization.UnicodeCategory.LowercaseLetter || | |
cat == System.Globalization.UnicodeCategory.UppercaseLetter || | |
cat == System.Globalization.UnicodeCategory.DecimalDigitNumber) | |
sb.Append(upper ? Char.ToUpper(s[i]) : Char.ToLower(s[i])); | |
upper = cat != System.Globalization.UnicodeCategory.LowercaseLetter && | |
cat != System.Globalization.UnicodeCategory.UppercaseLetter && | |
cat != System.Globalization.UnicodeCategory.NonSpacingMark; | |
} | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment