Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

sorting

I have strings like this:

var a = "ABCFE";

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

ABCEF

Thanks

like image 594
David H Avatar asked Jun 22 '11 14:06

David H


People also ask

How do I sort characters in a string?

The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.

How do you arrange a character in a string in alphabetical order in Python?

Use sorted() and str. join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the '+' operator.


2 Answers

You can use LINQ:

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

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

like image 127
SLaks Avatar answered Oct 22 '22 22:10

SLaks


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);
}
like image 45
Roy Dictus Avatar answered Oct 22 '22 21:10

Roy Dictus