Is there a simple way that I can sort characters in a string in alphabetical order

C#StringSorting

C# Problem Overview


I have strings like this:

var a = "ABCFE";

Is there a simple way that I can sort this string into:

ABCEF

Thanks

C# Solutions


Solution 1 - C#

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

Solution 2 - C#

Yes; copy the string to a char array, sort the char array, then copy that back into a string.

static string SortString(string input)
{
    char[] characters = input.ToArray();
    Array.Sort(characters);
    return new string(characters);
}

Solution 3 - C#

new string (str.OrderBy(c => c).ToArray())

Solution 4 - C#

You can use this

string x = "ABCGH"

char[] charX = x.ToCharArray();

Array.Sort(charX);

This will sort your string.

Solution 5 - C#

It is another.You can use SortedSet:

var letters = new SortedSet<char> ("ABCFE");
foreach (char c in letters) Console.Write (c); // ABCEF

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid HView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#Roy DictusView Answer on Stackoverflow
Solution 3 - C#agent-jView Answer on Stackoverflow
Solution 4 - C#Rupesh KambleView Answer on Stackoverflow
Solution 5 - C#shayan kamalzadehView Answer on Stackoverflow