Reverse the ordering of words in a string

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

    I know there are several correct answers. Here is the one in C that I came up with. This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.

    #include<stdio.h>
    
    char * strRev(char *str, char tok)
    {
       int len = 0, i;
       char *temp = str;
       char swap;
    
       while(*temp != tok && *temp != '\0') {
          len++; temp++;
       }   
       len--;
    
       for(i = 0; i < len/2; i++) {
          swap = str[i];
          str[i] = str[len - i]; 
          str[len - i] = swap;
       }   
    
       // Return pointer to the next token.
       return str + len + 1;
    }
    
    int main(void)
    {
       char a[] = "Reverse this string.";
       char *temp = a;
    
       if (a == NULL)
          return -1; 
    
       // Reverse whole string character by character.
       strRev(a, '\0');
    
       // Reverse every word in the string again.
       while(1) {
          temp = strRev(temp, ' ');
          if (*temp == '\0')
             break;
    
          temp++;
       }   
       printf("Reversed string: %s\n", a); 
       return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 11:13
    public static String ReverseString(String str)
    {
        int word_length = 0;
        String result = "";
        for (int i=0; i<str.Length; i++)
        {
            if (str[i] == ' ')
            {
                result = " " + result;
                word_length = 0;
            } else 
            {
                result = result.Insert(word_length, str[i].ToString());
                word_length++;
            }
        }
        return result;
    }
    

    This is C# code.

    0 讨论(0)
  • 2020-11-22 11:13

    We can insert the string in a stack and when we extract the words, they will be in reverse order.

    void ReverseWords(char Arr[])
    {
        std::stack<std::string> s;
        char *str;
        int length = strlen(Arr);
        str = new char[length+1];
        std::string ReversedArr;
        str = strtok(Arr," ");
        while(str!= NULL)
        {
            s.push(str);
            str = strtok(NULL," ");
        }
        while(!s.empty())
        {
            ReversedArr = s.top();
            cout << " " << ReversedArr;
            s.pop();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:13

    How about ...

    var words = "My name is X Y Z";
    var wr = String.Join( " ", words.Split(' ').Reverse().ToArray() );
    

    I guess that's not in-line tho.

    0 讨论(0)
  • 2020-11-22 11:13

    c# solution to reverse words in a sentence

    using System;
    class helloworld {
        public void ReverseString(String[] words) {
            int end = words.Length-1;
            for (int start = 0; start < end; start++) {
                String tempc;
                if (start < end ) {
                    tempc = words[start];
                    words[start] = words[end];
                    words[end--] = tempc;
                }
            }
            foreach (String s1 in words) {
                Console.Write("{0} ",s1);
            }
        }
    }
    class reverse {
        static void Main() {
            string s= "beauty lies in the heart of the peaople";
            String[] sent_char=s.Split(' ');
            helloworld h1 = new helloworld();
            h1.ReverseString(sent_char);
        }
    }
    

    output: peaople the of heart the in lies beauty Press any key to continue . . .

    0 讨论(0)
  • 2020-11-22 11:14

    Most of these answers fail to account for leading and/or trailing spaces in the input string. Consider the case of str=" Hello world"... The simple algo of reversing the whole string and reversing individual words winds up flipping delimiters resulting in f(str) == "world Hello ".

    The OP said "I want to reverse the order of the words" and did not mention that leading and trailing spaces should also be flipped! So, although there are a ton of answers already, I'll provide a [hopefully] more correct one in C++:

    #include <string>
    #include <algorithm>
    
    void strReverseWords_inPlace(std::string &str)
    {
      const char delim = ' ';
      std::string::iterator w_begin, w_end;
      if (str.size() == 0)
        return;
    
      w_begin = str.begin();
      w_end   = str.begin();
    
      while (w_begin != str.end()) {
        if (w_end == str.end() || *w_end == delim) {
          if (w_begin != w_end)
            std::reverse(w_begin, w_end);
          if (w_end == str.end())
            break;
          else
            w_begin = ++w_end;
        } else {
          ++w_end;
        }
      }
    
      // instead of reversing str.begin() to str.end(), use two iterators that
      // ...represent the *logical* begin and end, ignoring leading/traling delims
      std::string::iterator str_begin = str.begin(), str_end = str.end();
      while (str_begin != str_end && *str_begin == delim)
        ++str_begin;
      --str_end;
      while (str_end != str_begin && *str_end == delim)
        --str_end;
      ++str_end;
      std::reverse(str_begin, str_end);
    }
    
    0 讨论(0)
提交回复
热议问题