C# Alphabetize String

Letters of the alphabet: ABC

An individual string can be alphabetized. This rearranges the letters so they are sorted A to Z. These strings with sorted letters can be used as lookup keys. Here we see a method that alphabetizes strings in the C# programming language.

Input word/alphabetized string

sam   ams
spot  opst
cat   act

Example

The C# programming language

Here we see the Alphabetize method, which receives a C# string and returns a sorted copy of that string. Recall that strings are immutable, which means we cannot sort the letters in-place.

This C# Alphabetize method sorts the letters in strings. Complete source is available.

Program that alphabetizes strings [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(StringTools.Alphabetize("sam"));
	Console.WriteLine(StringTools.Alphabetize("spot"));
	Console.WriteLine(StringTools.Alphabetize("cat"));
    }
}

public static class StringTools
{
    /// <summary>
    /// Alphabetize the characters in the string.
    /// </summary>
    public static string Alphabetize(string s)
    {
	// 1.
	// Convert to char array.
	char[] a = s.ToCharArray();

	// 2.
	// Sort letters.
	Array.Sort(a);

	// 3.
	// Return modified string.
	return new string(a);
    }
}

Output

ams
opst
act

Description. The method converts the string to a char array using ToCharArray, which you can modify in-place. It uses the static Array.Sort method. This orders the letters from lowest to highest. The final line in the method creates a new string from the char[] array it modified, and returns it.

Why does it use ToCharArray?

Question and answer

For performance. You can change a character in a char array all by itself, which you cannot do with a string. I did some benchmarking and performance testing and this method turned out to be much faster than some others.

ToCharArray Method, Convert String to Array

Already alphabetical

You can find an interesting method that checks if each character in a string is alphabetical, which is useful before trying to use Array.Sort on the characters in your string. This provides clearer logic and a performance advantage, because no copying must be done and only one loop is required.

Alphabetical Chars Check

Summary

Note

Here we saw an efficient and simple method for alphabetizing strings. Don't use nested for loops, as that is a much slower N-squared complexity solution. This code may not work as you expect on mixed-case strings, which you can remedy by using ToLower in Alphabetize.

Sort Examples
.NET