Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created June 28, 2018 12:19
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 tkouba/d58eefcee4fb2d181f63418e698f951a to your computer and use it in GitHub Desktop.
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
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