Thaks for the time, normR1. I agree with u BestJew, but this seems to be logical question. This was the question i came across in an interview. Since, i knew that this can be solved by using either token or split with new arrays,but it should not be approched as such. Is there any other API which would reverse or any logic or approch?
Thanks normR1. Its just a logic question.No need to bother about database. Need to reverse words and keep it in buffer(i.e., some other variable). I don't knw the exact answer, atleast try with using some other java API (stack or queue..)
The easiest way to reverse a given string is to use reverse() method of java StringBuffer class. reverse() method returns the StringBuffer object so you'll need to cast it back to String using toString() method of StringBuffer
Well, it's not such a weird problem. K&R spend most of their time showing ways to rewrite library code, this is a good exercise.
We could assume that the input is a String, but then we have to assume some String methods, and then it's just too easy. So let's see what we can do with it as an array of char. The instructions say "no new array", so it's a fair assumption. :)
Okay, so we have an array of char, length unknown and contents unknown. To make life easier, I'll assume that it's an unpunctuated list of words, separated by spaces. If I could make a new array, life would be easy: walk backward from the end of the array until you hit a space. Mark that point. Walk forward and copy into the new array. Jump back to the marked point, repeat until zero.
Without that spare array, life's a little trickier, but this isn't so impossible. I see a way that involves a three-way swap, copying from both ends in to the middle. No stack or queue or API calls needed, you're moving one char at a time.
This is a C-type problem, more of a systems programming sort of thing than you're likely to deal with in Java, and hence very useful to wrangle with.
Okay, so it took me about an hour to get it working for the special case where the tokens being swapped are the same length. (ie, "frog is too to toad") Dealing with a sentence with arbitrary-length words will require some more bookkeeping, but I can say for sure that this is not an eminently solvable problem, and well worth the effort.
By the way, here's the one API call that you need to make:
char sentence = args.toCharArray();
That parses your command-line argument (put it in double quotes) into an array of char. Everything else is straight java.