Results 1 to 17 of 17

Thread: Reversing Strings???

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159

    Reversing Strings???

    I want to enter a sentence then reverse

    e.g.
    ==============================================

    Input

    Hello

    ==============================================

    ==============================================

    Output

    olleH

    ==============================================
    My mate said i should use the following methods

    Using a loop and the .charAt() method allso the .length() method.


    Any ideas


    Thanks

    James

  2. #2

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    By coincidence I had to do just that in my today's programming exam. It was part of a palindrome test:
    Code:
    public static bool isPalindrome(char[] word)
    {
      String normal = new String(word).toLowerCase();
      String reverse = new StringBuffer(normal).reverse().toString();
      return normal.equals(reverse);
    }
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159

    Reversing strings

    Im trying to learn loops, i think this could be a way too approach reversing strings. But im not sure how to approach the FOR loop.

    Like i said Using the .charAt() and the .length() method would be used.



    Code:
    String reverse;  // veriable
    
    
    System.out.println ("Please enter string to be reversed");
    reverse = UserInput.readString();
    
    for (?????????????????????????????????????){
    
            System.out.print (reverse);
    }
    Any help would be appritiated

    Thanks

    James

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Ah, ok.

    Strings are immutable, so you'll have to use a StringBuffer anyway.

    Code:
    String normal = "Hello";
    StringBuffer temp = new StringBuffer(normal.length());
    String reverse;
    for(int i=normal.length()-1;i>=0;--i) {
      temp.append(normal.charAt(i));
    }
    reverse = temp.toString();
    I run through the string from back to front, adding each character to the end of the string buffer. The result is the reversed string.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159
    would this be classed as a string??????????????

    Input

    Reverse me

  7. #7
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    What?
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159
    INSTEAD OF USING StringBuffer can you use a variable to store the information??????????

  9. #9
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    You could use a character array...
    Code:
    String normal = "Hello";
    char[] temp = new char[normal.length()];
    for(int i=0;i<normal.length;++i) {
      temp[i] = normal.charAt(normal.length()-(i+1));
    }
    String reverse = new String(temp);
    Is this what you want?
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159
    This is what i got

    Code:
        String reverse;
        String temp;     //???
    
        System.out.println ("Please enter string to be reversed");  
        reverse = UserInput.readString();
        
        StringBuffer temp = new StringBuffer(reverse.length());
    
        for(int i=reverse.length()-1;i>=0;--i) {
            temp.append(reverse.charAt(i));
        }
        
        reverse = temp.toString();
        
        System.out.println (reverse);
    it works this way but i was wondering instead of using the StringBuffer could i run the string from back to front, adding each character to the end of the temp veriable?

  11. #11
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    No, not really. As I said, a String is immutable. You could constantly redefine the string:
    Code:
    String reverse;
        String temp = "";
    
        System.out.println ("Please enter string to be reversed");  
        reverse = UserInput.readString();
        
        for(int i=reverse.length()-1;i>=0;--i) {
            temp = temp + reverse.charAt(i);
        }
        
        reverse = temp.toString();
        
        System.out.println (reverse);
    but that is extremly inefficient.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159
    This is what i wrote after the code i submitted but it didn't work but it does now for some strange reason. thanks anyway for your help

    so why is the code inefficient??

  13. #13
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    The code is inefficent simply because of the use of the loop. If you look at CornedBees first code fragment no loop is necessary only a reference to a char[] array passed in.

  14. #14
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    No, that's not the problem. Internally the StringBuffer.reverse method uses a loop too.
    The last one is inefficient because
    s = s + normal.charAt(i)
    doesn't append the character to s (as you probably think) but instead creates a new string object that it the concatenation of s and the character. The code is basically translated by the compiler to
    s = new StringBuffer().append(s).append(normal.charAt(i)).toString()
    which means you create a new StringBuffer and String object every loop iteration!
    This is terribly inefficient.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  15. #15
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    Right that's what i was getting at(but didnt feel like explaining)
    No loop is necessary thereby bypassing having to allocate memory on the fly multiple times.

    Funny question about this was just asked in class.
    Code:
    String s1 = 4 +"U"+"Only"; // is equivlent to
    
    String s2 = new StringBuffer().append(4).append("U").append("Only").toString();

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159
    WELL IF IT WORKS USING variables it works

    thanks for all your help

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Feb 2002
    Posts
    159

    Another small problem

    i wrote this piece of code

    Code:
    public class CheckBankAccount{
     public static void main(String[] argv) {
        
        int pinNo, userTries, counter;
        float cashAmount;
    
        //  Start of an endless loop since cashpoints never sleep.
        do {
    
            // Users name should appear
            BankAccount b = new BankAccount("James",1234);
            System.out.println(b.getName());
            
            // set the try counter to zero
            counter = 0;
            
            // loop to check max. 3 times for correct PIN starts here. 
            do {
    
                //ask user for PIN. 
                 System.out.println("Please enter your PIN");
       
                 // user enters PIN into the pinNo variable. 
                 pinNo = UserInput.readInt();
    
                 if (pinNo == 9999){
                    System.out.println ("bye");
                    System.exit(0);
                 }
                 
                 
                      
                 // increment counter for tries
                 ++ counter;
                 
            // end of the 'do' loop. Use a while here that checks if the PIN is incorrect AND
            // the counter for tries is smaller than 3
            } while(     (pinNo != 1234)   &&   (counter < 3)    );
                                          
                 
                 
            // this part of the program only executes if the counter for tries is smaller than 3
            // Use an if statement here that checks that.
            if (counter < 3) {
    
                // Ask how much the user wants to withdraw. 
                System.out.println("How much do you want to withdraw?");
    
                // User enters amount.
                cashAmount = UserInput.readFloat();
    
                // Print message confirming transaction: "You have withdrawn xxx Pounds" 
                System.out.println(" has withdrawn " +cashAmount+ " Pounds");
    
                // end of the if statement
            }
        // end of the endless 'do'-'while' loop. 
        } while (true);
    
        
        
     } // end of main
    } // end class
    I’m not sure on how to approach this problem

    if the user inputs the wrong PIN this message should appear

    "Invalid PIN, please try again"

    if the user inputs the PIN incorrect 3 times this message should appear.

    "3 x invalid PIN: aborting"

    and exit the program using the System.exit(0) function

    any ideas???

Posting Permissions

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



Click Here to Expand Forum to Full Width