Title: Convert camel case into underscore case in C#
Lately I've been doing a lot of C#-to-python conversion. The style in C# is to use camel case where you capitalize the first letter each each word after the first one in a variable's name as in thisIsAVariableName. The style in Python is underscore case where you separate the words in a name with underscores as in this_is_a_variable_name. Several studies have shown that underscore case is easier to read than camel case, but that's not the style in C# and some other languages.
Anyway, I wrote this program to make it slightly easier to convert from camel case to underscore case. If you enter the camel cased text in the upper text box and click Convert, the following surprisingly short code executes.
// Convert from TitleCase to underscore_case.
private void btnConvert_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
bool to_upper = chkUpperCase.Checked;
bool start_of_word = true;
foreach (char ch in txtTitleCase.Text)
{
if (char.IsUpper(ch))
if (!start_of_word) sb.Append("_");
if (to_upper)
sb.Append(ch.ToString().ToUpper());
else
sb.Append(ch.ToString().ToLower());
start_of_word = char.IsWhiteSpace(ch);
}
txtUnderscoreCase.Text = sb.ToString();
}
This code creates a StringBuilder, gets the input text, and sets start_of_word to true to indicate that the next letter will start a word. If then loops through the entered text letter-by-letter.
If a letter is in upper case, the code adds an underscore to the StringBuilder if this is not the start of a new word. That allows the code to convert either camelCase or PascalCase to underscore_case.
The code then adds the input character to the StringBuilder, converting the character to upper case if the Upper Case checkbox is checked. The code then sets start_of_word to true if the character was whitespace to indicate that the next non-whitespace character will start a new word.
After it has finished processing all of the input characters, the code returns the result.
Download the example to experiment with it and to see additional details.
|