Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

reverse order of word in string c#

One Line
public class Solution 
{
    public string ReverseWords(string s) 
      => string.Join(" ",s.Trim().Split(' ').Where(x=>x.Length>0).Reverse());
}

Another Approaches

public class Solution 
{
    public string ReverseWords(string s) 
    {
        var stack = new Stack<string>();
        int i=0 ,j=0;
        while(j <= s.Length)
        {
            if( j == s.Length || s[j] == ' ' )
            {
                var sub = s.Substring(i,j-i);
                if(j-i >= 0 && sub.Length > 0) stack.Push(sub); 
                i=++j;
            }
            else j++;
        }
        return string.Join(" ",stack);
    }
}
Source by leetcode.com #
 
PREVIOUS NEXT
Tagged: #reverse #order #word #string
ADD COMMENT
Topic
Name
7+4 =