Sort characters in a string

  • Thread starter Thread starter Someone
  • Start date Start date
S

Someone

Hi,

Using C# is there a quick, concise method of sorting the characters of a
string into alphabetic order
 
This is kinda hokey but seems to work:

string s = "zygwernmdkwirjdcndneyakdcmb";
char[] c=s.ToCharArray();
Array.Sort(c);
string s2=String.Empty;
foreach (char ch in c)
s2+=ch.ToString() ;
Console.WriteLine(s2);

--Peter
 
An optimization: to construct a string from a char[], just use the
string constructor.

public static string SortStringChars(string s)
{
char[] c=s.ToCharArray();
Array.Sort(c);
return new String(c);
}

Thi
 
Hi,

Peter Bromberg said:
This is kinda hokey but seems to work:

string s = "zygwernmdkwirjdcndneyakdcmb";
char[] c=s.ToCharArray();
Array.Sort(c);
string s2=String.Empty;
foreach (char ch in c)
s2+=ch.ToString() ;

You are creating a bIG number of strings here, just use the overloaded
constructor of String ( char[] ) or use StringBuilder instead.
 
Back
Top