1

I have a string of values that looks like this:

strSubjectIDs = "20,19,18,17,16,15";

Is there anyway to reverse that order of the string strSubjectIDs so that the IDs look like this:

"15,16,17,18,19,20"
frontin
  • 733
  • 2
  • 12
  • 28

2 Answers2

9
var reversedStr = string.Join(",", strSubjectIDs.Split(',').Reverse());
SimpleVar
  • 14,044
  • 4
  • 38
  • 60
0

This is the industry standard way to reverse the elements of a comma delimited string:

        string strSubjectIDs = "20,19,18,17,16,15";
        Console.WriteLine(strSubjectIDs);

        Queue<Char> q = new Queue<Char>();
        Stack<Queue<Char>> s = new Stack<Queue<Char>>();
        foreach(Char c in (strSubjectIDs.Trim(',') + ",").ToCharArray())
        {
            q.Enqueue(c);
            if (c == ',')
            {
                s.Push(q);
                q = new Queue<char>();
            }
        }
        while(s.Count > 0)
        {
            Queue<Char> t = s.Pop();
            while(t.Count > 0)
            {
                q.Enqueue(t.Dequeue());
            }
        }
        strSubjectIDs = new String(q.ToArray()).Trim(',');
        Console.WriteLine(strSubjectIDs);

Yeah, definitely; ask any professional programmer: Any algorithm not having a stack and/or a queue just isn't worth using.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40