C#Dot Net Perls

C#
Alphabetize String

by Sam Allen

Problem

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

C# Solution

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);
}
  1. The above method receives a string
    To use this method, you must pass it a C# string object.
  2. It uses ToCharArray
    The method converts the string to a char array using ToCharArray, which you can modify in-place.
  3. It returns a new string
    The final line in the method creates a new string from the char[] array it modified, and returns it.

Why use ToCharArray?

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.

How can I use the method?

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

Conclusion

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.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge