Sort characters in a string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Someone

    #1

    Sort characters in a string

    Hi,

    Using C# is there a quick, concise method of sorting the characters of a
    string into alphabetic order
  • Peter Bromberg [C# MVP]

    #2
    RE: Sort characters in a string

    This is kinda hokey but seems to work:

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

    --Peter
    --
    Co-founder, Eggheadcafe.com developer portal:

    UnBlog:





    "Someone" wrote:
    [color=blue]
    > Hi,
    >
    > Using C# is there a quick, concise method of sorting the characters of a
    > string into alphabetic order
    >[/color]

    Comment

    • Truong Hong Thi

      #3
      Re: Sort characters in a string

      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

      Comment

      • Ignacio Machin \( .NET/ C# MVP \)

        #4
        Re: Sort characters in a string

        Hi,

        "Peter Bromberg [C# MVP]" <pbromberg@yaho o.nospammin.com > wrote in message
        news:54980D64-67C4-4516-A866-EC2007723E7B@mi crosoft.com...[color=blue]
        > This is kinda hokey but seems to work:
        >
        > string s = "zygwernmdkwirj dcndneyakdcmb";
        > char[] c=s.ToCharArray ();
        > Array.Sort(c);
        > string s2=String.Empty ;
        > foreach (char ch in c)
        > s2+=ch.ToString () ;[/color]

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



        --
        Ignacio Machin,
        ignacio.machin AT dot.state.fl.us
        Florida Department Of Transportation


        Comment

        Working...