Alphabetize a string, rearranging the letters in a word or string so that they are arranged A to Z. Here's a nice table showing some words that we alphabetized like this. On the left is the input we pass to the function, and the right is what we want to get from it.
| If your input is | Then you want to receive |
| cat | act |
| senators | aeonrsst |
| alien | aeiln |
Alphabetizing is useful for normalizing combinations of letters and finding keys of unique frequencies of letters in a more general way. One challenge to writing this code in C# is that there are many different ways to accomplish this goal. This method uses standard framework functions and is fast, although not the fastest.
/// <summary>
/// Alphabetize the characters in the string.
/// </summary>
private static string Alpha(string wordIn)
{
// Copy the string to a char[] array, and then use the static
// Array.Sort function to sort that array. Finally, allocate a new
// string object and return it, for easy use in the rest of the app.
char[] arr = wordIn.ToCharArray();
Array.Sort(arr);
return new string(arr);
}
Performance. You can change a character in a character array all by itself, which you cannot do this with a .NET managed string. I did some benchmarking and performance testing and this method turned out to be much faster than some others. It creates fewer strings than many other ways.
First, the function Alpha can be declared as a static function because it doesn't need to use any state in the surrounding class. You can put this function in a static class, or a regular class. You can use the above method in the way shown by this example code.
string word = "cat"; Console.WriteLine(word); // Take the word variable, pass it to the Alpha function, and we // get the alphabetized version. (The lines above and below this block // are just for reporting. string alphaWord = Alpha(word); Console.WriteLine(alphaWord); // Will print out these two lines: // cat // act
Whatever you do, don't use nested for loops to do alphabetization--that is an N-Squared solution and many times slower in most cases. The way presented here won't bog down your processor unless it is run extraordinarily often. It is also shown at the code archive.