TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Alphabetize String

This C# article shows how to implement a string alphabetize method. The method sorts the letters in strings.

Alphabetize string. 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. To start, we see the Alphabetize method, which receives a C# string and returns a sorted copy of that string. Please recall that strings are immutable. This means we cannot sort the letters in-place.

C# program that alphabetizes strings

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

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.

And: The final line in the method creates a new string from the char array it modified, and returns it.

Char ArrayArray.Sort

Why does it use ToCharArray? 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.

ToCharArray

Already alphabetical. Some strings are already in alphabetical order. We can avoid sorting these strings. This enhances performance and results in simpler code. This method determines if the characters in a string are alphabetized.

Caution: This method compares the numeric values of chars, so it won't work right on uppercase letters.

Char Type

C# program that checks alphabetical strings

public static class StringTools
{
    /// <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;
    }
}

In this example, the IsAlpha method contains a foreach iterative statement that loops through each character in the string. 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.

Foreach Loop Examples

Tip: This kind of method has many purposes in applications, and is useful before checking if an array if any kind actually needs sorting.

Summary. We saw approaches for alphabetizing strings. It is typically a bad idea to use nested for-loops—that is often a slower solution. This code may not work on mixed-case strings. You can remedy this by using ToLower in Alphabetize.

ToLower


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf