-4

I am working on a code for homework where we have to use a char array holding a sentence and reverse the order of array so that the words are in opposite order in java for example "I am a house" should put out "house a am I" I am stuck on how to actually step through and order the array so the words go in this order any tips will help.

The code i have reverses the whole array but it does not put reverse it word by word

  if(sentence.length%2 == 0)
    {
        int middleR = sentence.length/2;
        int middleL = middleR - 1;
        for(int i = middleR; i < sentence.length; i++)
        {
            char temp = sentence[i];
            sentence[i] = sentence[middleL];
            sentence[middleL] = temp;
            middleL--;

        }

    }
    else
    {
        int middle = sentence.length/2;
        int end = sentence.length -1;

        for(int i = 0; i < middle;i++)
        {
            char temp = sentence[i];
            sentence[i] = sentence[end];
            sentence[end] = temp;
            end --;
        }

    }
  • What have you tried so far? Any code snippets that you can post? – aphrid Oct 03 '17 at 05:53
  • Hi, provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) please. – Rumid Oct 03 '17 at 05:55
  • Why do you think your code might do more than just reverse all the text? Are you asking why your code doesn't produce the output you expect, or for an algorithm that does? – David Ehrmann Oct 03 '17 at 06:04
  • Reverse the whole array; then find the word boundaries and reverse each portion of the array between those separately. – Andy Turner Oct 03 '17 at 07:21

1 Answers1

0

Split the text into an array of Strings (String.split), put the array into a List (Arrays.asList), revers the list (Collections.reverse), get String array from the list (List.toArray)

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275