反转逗号分隔的值字符串的顺序

时间:2015-01-25 23:31:34

标签: c# string reverse

我有一串看起来像这样的值:

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

无论如何要反转字符串strSubjectIDs的顺序,以便ID看起来像这样:

"15,16,17,18,19,20"

2 个答案:

答案 0 :(得分:6)

var reversedStr = string.Join(",", strSubjectIDs.Split(',').Reverse());

答案 1 :(得分:0)

这是反转逗号分隔字符串元素的行业标准方法:

        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);
是的,当然;问任何专业程序员:任何没有堆栈和/或队列的算法都不值得使用。