Reverse the ordering of words in a string

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

    Actually, the first answer:

    words = aString.split(" ");
    for (i = 0; i < words.length; i++) {
        words[i] = words[words.length-i];
    }
    

    does not work because it undoes in the second half of the loop the work it did in the first half. So, i < words.length/2 would work, but a clearer example is this:

    words = aString.split(" "); // make up a list
    i = 0; j = words.length - 1; // find the first and last elements
    while (i < j) {
        temp = words[i]; words[i] = words[j]; words[j] = temp; //i.e. swap the elements
        i++; 
        j--;
    }
    

    Note: I am not familiar with the PHP syntax, and I have guessed incrementer and decrementer syntax since it seems to be similar to Perl.

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

    reverse the string and then, in a second pass, reverse each word...

    in c#, completely in-place without additional arrays:

    static char[] ReverseAllWords(char[] in_text)
    {
        int lindex = 0;
        int rindex = in_text.Length - 1;
        if (rindex > 1)
        {
            //reverse complete phrase
            in_text = ReverseString(in_text, 0, rindex);
    
            //reverse each word in resultant reversed phrase
            for (rindex = 0; rindex <= in_text.Length; rindex++)
            {
                if (rindex == in_text.Length || in_text[rindex] == ' ')
                {
                    in_text = ReverseString(in_text, lindex, rindex - 1);
                    lindex = rindex + 1;
                }
            }
        }
        return in_text;
    }
    
    static char[] ReverseString(char[] intext, int lindex, int rindex)
    {
        char tempc;
        while (lindex < rindex)
        {
            tempc = intext[lindex];
            intext[lindex++] = intext[rindex];
            intext[rindex--] = tempc;
        }
        return intext;
    }
    
    0 讨论(0)
  • 2020-11-22 11:18

    In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).

    #include<stdio.h>
    #include<stdlib.h>
    main(){
      char* a = malloc(1000);
      fscanf(stdin, "%[^\0\n]", a);
      int x = 0, y;
      while(a[x]!='\0')
      {
        if (a[x]==' ' || a[x]=='\n')
        {
          x++;
        }
        else
        {
          y=x;
          while(a[y]!='\0' && a[y]!=' ' && a[y]!='\n')
          { 
            y++;
          }
          int z=y;
          while(x<y)
          {
            y--;
            char c=a[x];a[x]=a[y];a[y]=c; 
            x++;
          }
          x=z;
        }
      }
    
      fprintf(stdout,a);
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 11:18
    import java.util.Scanner;
    
    public class revString {
       static char[] str;
    
       public static void main(String[] args) {
        //Initialize string
        //str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
        //'r', 'l', 'd' };
        getInput();
    
        // reverse entire string
        reverse(0, str.length - 1);
    
        // reverse the words (delimeted by space) back to normal
        int i = 0, j = 0;
        while (j < str.length) {
    
            if (str[j] == ' ' || j == str.length - 1) {
    
                int m = i;
                int n;
    
                //dont include space in the swap. 
                //(special case is end of line)
                if (j == str.length - 1)
                    n = j;
                else
                    n = j -1;
    
    
                //reuse reverse
                reverse(m, n);
    
                i = j + 1;
    
            }
            j++;
        }
    
        displayArray();
    }
    
    private static void reverse(int i, int j) {
    
        while (i < j) {
    
            char temp;
            temp = str[i];
            str[i] = str[j];
            str[j] = temp;
    
            i++;
            j--;
        }
    }
    private static void getInput() {
        System.out.print("Enter string to reverse: ");
        Scanner scan = new Scanner(System.in);
        str = scan.nextLine().trim().toCharArray(); 
    }
    
    private static void displayArray() {
        //Print the array
        for (int i = 0; i < str.length; i++) {
            System.out.print(str[i]);
        }
    }
    

    }

    0 讨论(0)
  • 2020-11-22 11:19
    Not exactly in place, but anyway: Python:
    
    >>> a = "These pretzels are making me thirsty"
    >>> " ".join(a.split()[::-1])
    'thirsty me making are pretzels These'
    
    0 讨论(0)
  • 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(' ');
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题