Skip to content

Instantly share code, notes, and snippets.

@EdCharbeneau
Last active February 10, 2019 17:46
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 EdCharbeneau/7f26f3c7d28b1eec9fd97fea43cc8b4d to your computer and use it in GitHub Desktop.
Save EdCharbeneau/7f26f3c7d28b1eec9fd97fea43cc8b4d to your computer and use it in GitHub Desktop.
CamelCase to human readable
public static string SplitUpperCaseToString(this string source) {
return string.Join(" ", SplitUpperCase(source));
}
public static string[] SplitUpperCase(this string source) {
if (source == null) {
return new string[] {}; //Return empty array.
}
if (source.Length == 0) {
return new string[] {""};
}
StringCollection words = new StringCollection();
int wordStartIndex = 0;
char[] letters = source.ToCharArray(); char previousChar = char.MinValue;
// Skip the first letter. we don't care what case it is.
for (int i = 1; i < letters.Length; i++) {
if (char.IsUpper(letters[i]) && !char.IsWhiteSpace(previousChar)) {
//Grab everything before the current character.
words.Add(new String(letters, wordStartIndex, i - wordStartIndex));
wordStartIndex = i;
} previousChar = letters[i];
}
//We need to have the last word.
words.Add(new String(letters, wordStartIndex, letters.Length - wordStartIndex));
string[] wordArray = new string[words.Count];
words.CopyTo(wordArray, 0);
return wordArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment