Reverse the ordering of words in a string

后端 未结 30 3791
青春惊慌失措
青春惊慌失措 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.

提交回复
热议问题