Results 1 to 2 of 2
  1. #1
    mamoonrizwan is offline Member
    Join Date
    Apr 2011
    Posts
    19
    Rep Power
    0

    Default reversing words of a string using stacks

    i have succeeded in tokenizing and reversing the individual words using stacks but each word is a mirror of itself. how do i change it
    i want "electrical engineering department " to be "department engineering electrical"

    here goes my code





    import java.util.StringTokenizer;
    import java.util.Scanner;
    import java.util.Stack;

    public class ReverseWords{
    public static void main (String args[]){

    Scanner scan = new Scanner(System.in);
    String original = scan.nextLine();
    StringTokenizer string = new StringTokenizer(original);

    Stack<Character> charStack = new Stack<Character>();

    while (string.hasMoreTokens()){

    String temp = string.nextToken();

    for (int i = 0; i < temp.length(); i ++){

    charStack.push(temp.charAt(i));
    }
    charStack.push(' ');
    }

    StringBuilder result = new StringBuilder();
    while(!charStack.empty()){
    result.append(charStack.pop());

    }

    System.out.println(result.toString());


    }


    }

  2. #2
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    5

    Default Re: reversing words of a string using stacks

    Why not have a stack of Strings and push scan.nextLine() to it?

Similar Threads

  1. Reverse words of string.
    By Vikash Kumar Singh in forum Advanced Java
    Replies: 6
    Last Post: 08-07-2011, 01:28 PM
  2. Removing words from a String
    By nn12 in forum New To Java
    Replies: 3
    Last Post: 03-15-2011, 11:50 AM
  3. Reversing the String
    By Inaam in forum New To Java
    Replies: 1
    Last Post: 03-30-2009, 09:35 PM
  4. Reversing String
    By mew in forum New To Java
    Replies: 4
    Last Post: 12-02-2007, 10:42 PM
  5. reversing a string
    By toad in forum New To Java
    Replies: 5
    Last Post: 11-07-2007, 10:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •