-2

So im trying to reverse the words in a sentence like: "Hi dog cat", would become "iH god tac". I was wondering if i can use what im doing to achieve that. I can get the sentence itself to reverse, but i cant get individual words to do so. Is there a way to do this with Strings or do i have to mess with Character(which is confusing too)? Any help is appreciated

    private static String PrintStack(String sentence)
    {
        String reverse = "";
        String stringReversed = "";
        String Last;
        String First;

        Stack<String> stack= new Stack<String>();

        String words[] = sentence.split(" ");
        Last = words[words.length-1];

        for(int j = 0; j < words.length; j++)
        {
            String newWord = words[0+j];
            stack.push(newWord);
            System.out.println(stack);
        }

        while(!stack.isEmpty())
        {
            stringReversed += stack.pop();
        }

        System.out.println("Reverse is: " + stringReversed);


        return reverse;
    }   
}
user3071909
  • 15
  • 3
  • 3
  • 9
  • Single-character strings, or Character. Or implement a non-object stack and use chars. Pick one. – keshlam Feb 13 '14 at 03:47
  • Hi, if you look to the right (===>), the Related links shows several similar questions. If you spend 10 seconds doing a search on SO, you would find similar questions that have been answered. Please read [help] and [ask]. – OldProgrammer Feb 13 '14 at 03:49

1 Answers1

0

FYI in Java it's conventional to name methods and variables with lowercase first letters, e.g., "printStack().

Your algorithm doesn't reverse the words themselves. I'd do it like this:

private static String reverseWords(String sentence) {
    String words[] = sentence.split(" ");
    ArrayList<String> reversed = new ArrayList<String>();
    for (String word : words) {
        reversed.add(new StringBuilder(word).reverse().toString());
    }
    StringBuilder reversedSentence = new StringBuilder();
    for (String word : reversed) {
        reversedSentence.append(word);
        reversedSentence.append(" ");
    }
    return reversedSentence.toString().trim();
}

Hope this helps,

--Mark

Mark Phillips
  • 1,451
  • 13
  • 17