C#将输入的一句话中的所有单词倒置

问题来自百度知道:

C#将输入的一句话中的所有单词倒置_第1张图片

要求不要开辟另外的内存空间,我应该没做到。但至少效果实现了。

我的方法是:

        static void Main(string[] args)
        {
            string sentence = "Recetly, hospitals in many";
            Console.WriteLine("  原来的句子:" + sentence);
            Console.WriteLine("处理后的句子:" + ReverseSentence(sentence));
            Console.Read();
        }

        static string ReverseSentence(string sentence) 
        {        
            char[] chars = sentence.ToCharArray();
            sentence = "";
            for (int i = chars.Length - 1; i >= 0; i--)
            {
                sentence += chars[i];
            }
            //Console.WriteLine(sentence);
            Regex regex = new Regex(@"(\b\w+\b)|(\W+)");
            MatchCollection matches = regex.Matches(sentence);
            //Console.WriteLine(matches.Count);
            string str = "";
            for (int i = matches.Count - 1; i >= 0;i-- )
            {
                str += matches[i].ToString();
            }
            return str;
        }

运行结果:   

 


那个逗号的位置不对,下面是修改后的:

	static void Main(string[] args)
        {
            string sentence = "Recetly, hospitals in many";
            Console.WriteLine("  原来的句子:" + sentence);
            Console.WriteLine("处理后的句子:" + ReverseSentence(sentence));
            Console.Read();
        }

        static string ReverseSentence(string sentence)//反转句子
        {
            sentence = ReverseString(sentence.Trim());
            Regex regex = new Regex(@"(\b\w+\b)|(\W+)");
            MatchCollection matches = regex.Matches(sentence);
            string str = "";
            for (int i = matches.Count - 1; i >= 0; i--)
            {
                if(i%2 == 0)
                {
                    str += matches[i].ToString();
                }
                else
                {
                    str += ReverseString(matches[i].ToString());
                }
            }
            return str;
        }
	static string ReverseString(string str)//反转单个字符串
        {
            char[] chars = str.ToCharArray();
            str = "";
            for (int i = chars.Length - 1; i >= 0; i--)
            {
                str += chars[i];
            }
            return str; 
        }

运行结果:




你可能感兴趣的:(String,C#,百度,regex)