Reverse the ordering of words in a string

后端 未结 30 4187
青春惊慌失措
青春惊慌失措 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:00

    Better version
    Check my blog http://bamaracoulibaly.blogspot.co.uk/2012/04/19-reverse-order-of-words-in-text.html

    public string reverseTheWords(string description)
    {
        if(!(string.IsNullOrEmpty(description)) && (description.IndexOf(" ") > 1))
        {
            string[] words= description.Split(' ');
            Array.Reverse(words);
            foreach (string word in words)
            {
                string phrase = string.Join(" ", words);
                Console.WriteLine(phrase);
            }
            return phrase;
        }
        return description;
    }
    

提交回复
热议问题