第10 题翻转句子中单词的顺序

翻转句子中单词的顺序。
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”。

思路:把字符串按空格分割成数组,然后倒序拼接输出

但是:出题人的意图是不让你用string里的方法分割拼接。最后我只能自己想办法反转了,如果不用string里的方法有点小复杂!

方法一:

          string str = "I am a student.";

           string[] oldStr = str.Split(' ');

           Array.Reverse(oldStr);

           string newStr = string.Join(" ", oldStr);

方法二:

class Program
    {
        static void Main(string[] args)
        {
          
           string str = "I am a student.";
           string newStr = GetStrReverse(ref str);
           Console.WriteLine(newStr);
           Console.ReadKey();

        }
        public static string GetStrReverse(ref string str)
        {

            if (str == null || str == string.Empty)
            {

                throw new ArgumentException("请输入需要反转的字符!", "错误参数:str");

            }

            //全部反转            

            StringBuilder currentStr = new StringBuilder(str.Length);

            for (int i = str.Length - 1; i >= 0; i--)
            {

                currentStr.Append(str[i]);

            }

            #region 单词顺序复原

            char tempChar;

            int indexBegin = 0;

            int indexEnd = 0;

            for (int i = 0; i < currentStr.Length; i++)
            {

                if (currentStr[i] == ' ')
                {

                    indexEnd = i - 1;     //字符串结束的位置

                   while (indexBegin < indexEnd)    //字符串倒转
                    {

                        tempChar = currentStr[indexBegin];

                        currentStr[indexBegin] = currentStr[indexEnd];

                        currentStr[indexEnd] = tempChar;

                        indexBegin++;

                        indexEnd--;

                    }

                    indexBegin = i + 1;//跳过空格,下个字符串开始的位置               

                }

                /*else if (currentStr[i] == '!' || currentStr[i] == ',' ||

                currentStr[i] == '.' || currentStr[i] == ';' || currentStr[i] == '?')
                {

                    indexBegin = i + 1; //跳过标点符号,标点符号位置不变              

                }*/

            }

            #endregion

            return currentStr.ToString();

        }


    }

posted @ 2011-07-24 18:11  meifage2  阅读(408)  评论(0编辑  收藏  举报