C# .NET - how to split string and arrange in ascending order in c#.net

Asked By mani on 07-Jan-12 06:24 AM
hi..i have following string as

A3;A2;A5;A1;A4

like this...
i can split it by semicolon..
but how can i arrange it in

A1;A2;A3;A4;A5 like this..
any help appreciated????
Sreekumar P replied to mani on 07-Jan-12 06:34 AM
Hi,

Use this code to get the same u told,

string input = "A3;A2;A5;A1;A4";
    string[] splits = input.Split(';');
    Array.Sort(splits);
    string output = "";
    foreach (string a in splits)
    {
      output += "," + a;
    }
    output = output.Remove(0, 1);


output variable will contain A1,A2,A3,A4,A5
Riley K replied to mani on 07-Jan-12 06:47 AM


Here is the way, but if you would have tried you could improve your skills


what i have done is split the using the Split method and storing in list and iterating and displaying 

string str = "A3;A2;A5;A1;A4";
      List<string> names = str.Split(';').ToList<string>();
      names.Sort();
 
      string newString = string.Empty;
      foreach (string s in names)
      {
        newString += s.ToString() + ";";
      }
      Console.WriteLine(newString);
      Console.ReadLine();

output
A1;A2;A3;A4;A5;


Regards
[)ia6l0 iii replied to mani on 07-Jan-12 10:45 AM
LinQ?

string completeString = "A3;A2;A5;A1;A4";
var array = completeString.Split(new char[] { ';' }).OrderBy(s => s.ToString());