问题来自百度知道:

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

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

我的方法是:

        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;
        }

运行结果:   

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

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

	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; 
        }


运行结果:

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2022-12-23
  • 2022-01-21
  • 2021-10-02
  • 2022-12-23
  • 2021-04-19
猜你喜欢
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
  • 2022-12-23
  • 2021-06-12
  • 2022-12-23
相关资源
相似解决方案