Reverse the ordering of words in a string

后端 未结 30 4241
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:21

    Printing words in reverse order of a given statement using C#:

        void ReverseWords(string str)
        {
            int j = 0;
            for (int i = (str.Length - 1); i >= 0; i--)
            {
                if (str[i] == ' ' || i == 0)
                {
                    j = i == 0 ? i : i + 1;
    
                    while (j < str.Length && str[j] != ' ')
                        Console.Write(str[j++]);
                    Console.Write(' ');
                }
            }
        }
    

提交回复
热议问题