上机题目

请编写一个方法,实现如下功能:

  删除输入的任意字符串中所有最邻近的 "<" 和 ">" 之间的字符,将其余字符返回。

  public string GetTrimChar(string strInput)

  例1:输入<123><456>4<5</456></123>

    输出4<5

  例2:输入ab<1b2>cd<a23>e>

    输出abcde-

  注:不能使用正则表达式

        static void Main(string[] args)
        {
            string strArg1 = "<123><456>4<5</456></123>";
            string str1 = GetTrimChar(strArg1);
            System.Console.WriteLine(str1);
            string strArg2 = "ab<1b2>cd<a23>e>";
            string str2 = GetTrimChar(strArg2);
            Console.WriteLine(str2);


            Console.ReadKey();
        }

        static string GetTrimChar(string strArg)
        {
            if (strArg == null || strArg.Length <= 0)
            {
                return "";
            }

            char[] chArray = strArg.ToArray();
            Stack<char> chStack = new Stack<char>();
            for (int i = chArray.Length - 1; i >= 0; i--)
            {
                if (chArray[i] == '<')
                {
                    var tempList = chStack.Where(x => x == '>');
                    if (tempList.Count() > 0)
                    {
                        while (true)
                        {
                            char temp = chStack.Pop();
                            if (temp == '>')
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        chStack.Push(chArray[i]);
                    }
                }
                else
                {
                    chStack.Push(chArray[i]);
                }
            }

            return string.Join("", chStack.ToList());
        }

 

posted @ 2020-08-28 09:44  智者见智  阅读(88)  评论(0编辑  收藏  举报