首页 > 解决方案 > 如何从结尾 c# 反转字符串 2 个字符和 2 个字符

问题描述

样品string

A3148579

预期结果:

798514A3

我试过这段代码:

 public static string Reverse(string s)
 {
     char[] charArray = s.ToCharArray();

     Array.Reverse(charArray);

     return new string(charArray);
 }

实际结果9758413A

但我想要798514A3

在此处输入图像描述

感谢大家

标签: c#.netalgorithm

解决方案


You can try below code. This is just to give you a idea and you can update based on the test cases and requirement. Below code works fine for your input which you have mentioned. I have not considered if the length is odd. You can do your research and update logic which will help you to learn and know more.

string input = "A3148579";
            Stack stack = new Stack();
            int count = 0;
            string output = "";

            for (int i = 0; i < input.Length/2; i++)
            {
                stack.Push(input.Substring(count, 2));
                count = count + 2;
            }

            while (stack.Count > 0)
            {
                output += stack.Pop().ToString();
            }

推荐阅读