Alphabetize string. In C# 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.
We can alphabetize characters in a string, but we do not always need to. Consider the case of the string "abc": it does not need to be alphabetized again.
Example method. Here we see a method that alphabetizes strings in the C# programming language. The method receives a string and returns a sorted copy of that string.
using System;
class Program
{
static void Main()
{
Console.WriteLine(Alphabetize("bird"));
Console.WriteLine(Alphabetize("spot"));
Console.WriteLine(Alphabetize("cat"));
}
/// <summary>/// Alphabetize the characters in the string./// </summary>
public static string Alphabetize(string s)
{
// Convert to char array.
char[] a = s.ToCharArray();
// Sort letters.
Array.Sort(a);
// Return modified string.
return new string(a);
}
}bdir
opst
act
Already alphabetical. Some strings are already in alphabetical order. We can avoid sorting these strings. Here we see a method that tests for alphabetical order—it can improve performance.
Note IsAlpha compares the numeric values of chars, so it won't work right on uppercase letters.
And If it finds a character that is lower in its ordinal value than the previous character, it returns false.
Also It returns early when it finds an incorrect (non-alphabetized) character. In this situation, no further processing is needed.
using System;
class Program
{
static void Main()
{
Console.WriteLine(IsAlpha("abc"));
Console.WriteLine(IsAlpha("bird"));
}
/// <summary>/// Alphabetize string, checking to see if it is already alphabetized./// </summary>
public static string AlphabetizeCheck(string s)
{
if (IsAlpha(s))
{
return s;
}
else
{
// TODO: Sort and return the new string.
return "";
}
}
/// <summary>/// See if letters in string are in numeric ascending order./// </summary>
public static bool IsAlpha(string s)
{
char prev = char.MinValue;
foreach (char c in s)
{
if (c < prev)
{
return false;
}
prev = c;
}
return true;
}
}True
False
A summary. We saw approaches for alphabetizing strings. It is typically a bad idea to use nested for-loops—that is often a slower solution.
A final note. This code may not work on mixed-case strings. We can remedy this by calling ToLower in Alphabetize—this is not always be needed.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 23, 2023 (edit).