Sort characters of a string in alphabetical order in C#
This article illustrates the different techniques to sort characters of a string in alphabetical order in C#.
We can use LINQ to sort characters of a string in alphabetical order in C#. The idea is to use LINQ’s OrderBy() method to create a sorted collection of all characters in the string, and then combine all characters together with the String.Concat() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { String s = "SHdRVBAHskaBJSyHfD"; s = String.Concat(s.OrderBy(ch => ch)); Console.WriteLine(s); // ABBDHHHJRSSVadfksy } } |
Another option is to convert the string to a character array and sort it, and then pass the sorted character array to the string constructor to get a sorted string instance. The following code example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Linq; public static class StringExtensions { public static String Sort(this String input) { char[] chars = input.ToCharArray(); Array.Sort(chars); return new String(chars); } } public class Example { public static void Main() { String s = "SHdRVBAHskaBJSyHfD"; s = s.Sort(); Console.WriteLine(s); // ABBDHHHJRSSVadfksy } } |
That’s all about sorting characters of a string in alphabetical order in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)