Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: Reversing a String with no Buffer

  1. #1
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Reversing a String with no Buffer

    i was wondering if anybody can give me some help with drawing out the logic behind reversing a string with the following results: sample = "My name is jack"; the reverse should display "yM eman si kcaj".... i know how to reverse the entire string but in this case how would i reverse the letters but keep the words in their same position???


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Reversing a String with no Buffer

    Please don't double post questions. Your duplicate has been closed.

    As for your problem, how would you do this logically? What are the individual steps necessary to achieve this on paper if you had a lot of words to go through? Now try to translate this logic into pseudo-code, and then code. Then if you get stuck at one step, please ask away.

  3. #3
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    didnt know it duplicated my connection got lost as soon as i hit post.... would i need a variable to specify the white space and another string variable for the new result??? also would it make a difference if i assigned the sample to a char array variable or can i just use String?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reversing a String with no Buffer

    What does "with no buffer" mean?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    without using a StringBuffer object....

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Reversing a String with no Buffer

    So you could just use a String and concatenate your building String to it. You need to parse your original String into words, and then work on each word. I'm thinking that I would write methods for both steps.

  7. #7
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    ok i thought there would be a faster way using simple for loops and maybe an if statement.... so i should make a method to separate the string of words into let's say, a String array and then another method to reverse each String element and return the result???

  8. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Reversing a String with no Buffer

    Strings are immutable, you're going to need some sort of mutable char sequence to work with. Good class choices are StringBuilder and StringBuffer which only differ from each other in implementation details (StringBuffer is thread-safe, StringBuilder is not).

    Since you're not allowed to use these, the next option is to use a char array, or Character ArrayList and do the reversing manually (preference to char array, there are built-in mechanisms for converting between Strings and char arrays).

    Done smartly you can get away with doing the reversals all in-place (assuming you have the whole string as a mutable char sequence), but you will still need to loop through the string looking for the spaces.

    If you really can't use either char arrays or the StringBuilder/StringBuffer classes, you'll have to manually concatenate the words into reverse order (still need to find where the spaces are), then put the words back together using string concatenation. Not efficient at all, but it will get the job done.

  9. #9
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    ok i read something about a char array but wasnt sure of its importance... so turn the input into a char array and then make a method that returns a string? how would i turn the char array into separate words?? by making the method return a String array???

  10. #10
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Reversing a String with no Buffer

    I beg to differ. While Strings are immutable, a String variable can easily be reassigned a new reference. The easiest way to solve this is with simple String concatenation.

    get String to be reveresed
    split String via the split(...) method into an array of words.
    create empty result String
    for loop, looping over the array
       concatenate to the result String the reverse of the next word in array. Call a method to get the reverse word.
    end for loop

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reversing a String with no Buffer

    Using the split() method will be ok if there is always only one space between words or if it is not important to preserve extra spaces.
    The right regex might preserve the extra spaces in the array.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Reversing a String with no Buffer

    Err, yeah, I kind of alluded to that method in my last paragraph which contradicts my first sentence

    If you're using a char array type solution I wouldn't have multiple char arrays for each word as only one is needed for the entire string.

    I would do something like this:

    reverseSentenceString(string):
        convert original string to char array
        initialize a word begin index
        for each character in the array:
            if the current character is a whitespace:
                reverseSubstring(char array, word begin index, current index)
                set word begin index = current index + 1
        return new string from char array
     
    reverseSubstring(char[] buffer, start_index, end_index):
        for each index from start_index up to half way through the selected region:
            swap buffer[index] and buffer[end_index - index]

    Similar solutions apply for using StringBuilder/StringBuffer.

    This of course assumes that the temporary char array isn't considered a buffer, otherwise curmudgeon's solution would be the way to go

  13. The Following User Says Thank You to helloworld922 For This Useful Post:

    curmudgeon (March 10th, 2013)

  14. #13
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    call a method to reverse the current element in the array and then something like empty += revStr[x];
    thanks for that nugget i think that's what i needed to write this

    --- Update ---

    wow i definitely wasnt thinking that much i had another plan n mind with more methods than two... thanks for the pseudo both of u

  15. #14
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    how would i swap char elements??? i have a code but where do i go from here
    /*
     * Reverse a string but keep the words in their original positions
     */
     
    import javax.swing.*;
     
    class ReverseString {
     
        String inputStr;
        char[] charArray;
     
        public static void main(String[] args) {
            ReverseString revStr = new ReverseString();
            revStr.reverseSentence();
        }
     
        private void reverseSentence(){
     
            inputStr = JOptionPane.showInputDialog(null, "Enter a sentence:");
     
            charArray = inputStr.toCharArray();
     
            char beginIndex = charArray[0];
            char whiteSpace = ' ';
     
            for(int i = 1; i < charArray.length; i++){
                if(charArray[i] == whiteSpace){
                    reverseSubstring(charArray, beginIndex, charArray[i]);
                    beginIndex = charArray[i + 1];
                }
            }
        }
     
        private void reverseSubstring(char[] array, char startIndex, char endIndex){
            for(int i = startIndex; i < endIndex; i++){
                int temp;
     
            }
        }
    }

  16. #15
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Reversing a String with no Buffer

    You're not actually keeping track of the indices, you're tracking the actual characters. That means you won't know what elements in the array to swap (Java tracks primitives by value only so you can't use references/pointers to swap as you could with C/C++).

    Swap is fairly easy:

    swap(A, B):
    temp = A
    A = B
    B = temp

  17. #16
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    so i would add another method to do the swap or should i just go ahead and keep coding in the for loop???

  18. #17
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Reversing a String with no Buffer

    You don't need a dedicated swap method, but you could. I usually don't because it's pretty trivial and short enough to inline everywhere I need to swap. Also Java doesn't allow referencing/pointing to primitives so sometimes you can't really use a dedicated method without some unnecessary object/array wrapper layer.

  19. #18
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    would i use an int as the temp variable even tho im swapping char elements??? it says the precision might be lost if i use char

  20. #19
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Reversing a String with no Buffer

    You should be using a temporary char, and there should be no loss of precision warning if you have it right. Could you post your code?

  21. #20
    Member
    Join Date
    Jul 2012
    Posts
    71
    Thanks
    1
    Thanked 7 Times in 7 Posts

    Default Re: Reversing a String with no Buffer

    it's still a little buggy
    /*
     * Reverse a string but keep the words in their original positions
     */
     
    import javax.swing.*;
     
    class ReverseString {
     
        String inputStr;
        char[] charArray;
     
        public static void main(String[] args) {
            ReverseString revStr = new ReverseString();
            revStr.reverseSentence();
        }
     
        private void reverseSentence(){
     
            inputStr = JOptionPane.showInputDialog(null, "Enter a sentence:");
     
            charArray = inputStr.toCharArray();
     
            char beginIndex = charArray[0];
            char whiteSpace = ' ';
     
            for(int i = 0; i < charArray.length; i++){
                if(charArray[i] == whiteSpace){
                    reverseSubstring(charArray, beginIndex, charArray[i]);
                    beginIndex = charArray[i + 1];
                }
                System.out.print(charArray[i]);
            }
        }
     
        private void reverseSubstring(char[] array, char startIndex, char endIndex){
            for(int i = startIndex; i < endIndex; i++){
                int temp;
                temp = array[startIndex];
                array[startIndex] = array[endIndex];
                array[endIndex] = (char) temp;
            }
        }
    }

  22. #21
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Reversing a String with no Buffer

    Yeah, temp should be a char and that should fix the loss of precision warning/need for a cast.

Similar Threads

  1. Reversing a String with no Buffer
    By C++kingKnowledge in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 10th, 2013, 12:17 PM
  2. Java String Buffer
    By anonb in forum Object Oriented Programming
    Replies: 3
    Last Post: December 19th, 2012, 02:59 AM
  3. Reversing an Array
    By georger55 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 8th, 2012, 07:22 AM
  4. [SOLVED] difference between String Concatenation and String -Buffer/Builder .append(<value>)
    By chronoz13 in forum Java Theory & Questions
    Replies: 5
    Last Post: September 3rd, 2011, 08:16 AM
  5. Reversing an array
    By severus1 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: June 30th, 2011, 03:54 PM