0

About reverse word using StringBuffer without using String.split.
For example reverse
Hello world
The output must

    olleh dlrow

not

    dlrow olleh

any idea to make this program??

Mat
  • 202,337
  • 40
  • 393
  • 406
heyman
  • 375
  • 2
  • 4
  • 16

3 Answers3

0

Import the library and use this function.

import org.apache.commons.lang.StringUtils;

String reverseWords(String string) {
    return StringUtils.reverseDelimited(StringUtils.reverse(string), ' ');
}
vikiiii
  • 9,246
  • 9
  • 49
  • 68
0

This sounds like a homework question, so instead of giving you actual code I will tell you what I have in mind using pseudocode.

Assumption: You have to do it in place using one StringBuffer only. Words are separated by space. You cannot use anything other than StringBuffer.

You will need to write a method called reverse

/**
 * This method reverse the word starting at startIndex 
 * and of length wordLength. For example:
 * StringBuffer buf = new StringBuffer("hello world");
 * reverse(buf, 0, 5);
 * will result in buf being "olleh world"
 */
reverse(StringBuffer s, int startIndex, int wordLength)

/* Now the pseudo code */
Given StringBuffer sb;
Find all the indexes of all the spaces in sb;
Using the indexes found to calculate the startIndex of each word and the lengths of the word;
call reverse for each of the calculated indexes and lengths;

Note: This is only one of the many ways to solve your problem.

Alvin
  • 10,308
  • 8
  • 37
  • 49
0

Here is one way to proceed:

User a result buffer to store the final string reversed word by word
Use a temp buffer to store each word you fond in the original string

Iterate over the chars in your buffer.
    // Identify a word: a word is terminated when you find a space
    If the actual char is not space then save it to temp buffer
    If the actual char is a space then you have a word witch is stored in temp buffer
        reverse that temp buffer and add it to the result buffer
        add a space the the result buffer
        clear the temp buffer so you can save the next word in it

Here is how it looks like in code

Removed since this is homework ;-)

Input:

"   HeLlo   world   "

Output:

'   olLeH   dlrow   '
A4L
  • 17,353
  • 6
  • 49
  • 70