String Reverse

A

Amit Jain

How can I reverse a given string without using String or StringBuffer
class method.
 
L

Lasse Reichstein Nielsen

Amit Jain said:
How can I reverse a given string without using String or StringBuffer
class method.

1. Why would you?
2. What String will you reverse if you don't use String?
And how will you represent the result without using a String?
3. Are you thinking of extracting the chars into an array and
reversing them there? Take care with multi-char Unicode characters :)

/L
 
R

Roedy Green

How can I reverse a given string without using String or StringBuffer
class method.

This obviously an artificial exercise since no one in their right mind
would avoid the built-in StringBuffer/StringBuilder/String methods.

The basic idea is a create char array the correct length, the fill it
one by one from your original string in a loop. Then when you are
done you convert the char[] to a String.

See http://mindprod.com/jgloss/conversion.html
 
D

Daniel Pitts

Amit said:
How can I reverse a given string without using String or StringBuffer
class method.
What is the sound of one hand clapping?
You can't reverse a string unless you have a string, now can you?

If you already have a string, you can *print* the reverse if it by
counting backward from the end of it, and printing each character along
the way.
 
P

Piotr Kobzda

Amit said:
How can I reverse a given string without using String or StringBuffer
class method.

new StringBuilder( givenString ).reverse().toString();


piotr
 
P

Piotr Kobzda

Daniel said:
What is the sound of one hand clapping?

Whoosh? :)
If you already have a string, you can *print* the reverse if it by
counting backward from the end of it, and printing each character along
the way.

That way some methods of String will still be used indirectly (when
allowed, I prefer my earlier suggestion).

The only way I know to achieve the result without touching any of String
methods is to reflectively access String's internals (i.e. value,
offset, and count fields). And then create a new String (we can use
constructors, they are not a methods) with the reversed chars of the
value array copy. That way is of course never guarantied to work, and
is rather awful hack than the solution. Thus, one should even try to do
that!


piotr
 
R

Roedy Green

new StringBuilder( givenString ).reverse().toString();

I think the intent of the exercise is to solve it without using a
built-in reverse method. The prof wants his students to do a simple
char by char string building exercise.
 
W

Walter Milner

I think the intent of the exercise is to solve it without using a
built-in reverse method. The prof wants his students to do a simple
char by char string building exercise.

Hey Amit are you still with us?

The standard recursive and fun way to do this is (in pseudo-code)

if length of string is 1, return string
else
return reverse(string without first character) joined with first
character
 
C

Chris Dollin

Walter said:
The standard recursive and fun way to do this is (in pseudo-code)

if length of string is 1, return string
else
return reverse(string without first character) joined with first
character

BOOM.

(reverse the empty string.)
 
S

Stefan Ram

Amit Jain said:
How can I reverse a given string without
using String or StringBuffer class method.

The statement

java.lang.System.out.println( "Hello!" );

can be split in a model and a view.

The model (»"Hello!«) is the internal storage of the code
points H-e-l-l-o-!, the View (»println«) displays this as

Hello!

One can as well adopt the point of view that for the string
model it makes no sense to »reverse« anything, because the
same model can also be viewed as a storage of the reversed
string, because whether to display the stored code points
H-e-l-l-o-! as

Hello!

or as

!olleH

is solely a question of the View, just as the color of the
characters used to display it or the size of the font.

From such a point of view, every string model already /is/
also a model of the reversed string, without the need for
an explicit computation to »determine« the reverse string.

(Admittedly, this point of view is not helpful in some cases.)
 
P

Piotr Kobzda

Roedy said:
I think the intent of the exercise is to solve it without using a
built-in reverse method. The prof wants his students to do a simple
char by char string building exercise.

Yes, probably.

But I was wondering if it's possible to correctly answer the OP's
question taken "as is", without making any unsound assumptions.

The problematic is even access to the String's length or chars without
using its methods.

Fortunately there is no mention about StringBuilder in the OP's
question, that's why I used it.


BTW -- If the prof intent was different, he, or she should clearly state
that. Otherwise, there is a huge number of solutions other than just
replace char by char.

Just one example more:

String reversed = "";
for(String s : java.util.regex.
Pattern.compile("").split( givenString )) {
reversed = s + reversed;
}


piotr
 
L

lord.zoltar

I think the intent of the exercise is to solve it without using a
built-in reverse method. The prof wants his students to do a simple
char by char string building exercise.

....Then he should make them do it in C.
 
M

Mike Schilling

Piotr Kobzda said:
new StringBuilder( givenString ).reverse().toString();

The Javadoc says that this handles surrogate pairs correctly, making it an
excellent answer.
 
A

Amit Jain

for example i have string

String temp = "Java";

and I need some sort of code which reverse this string without using
any String or other class method
 
T

Thomas Schodt

Amit said:
for example i have string

String temp = "Java";

and I need some sort of code which reverse this string without using
any String or other class method

You just restated your task without giving any additional clarification.
What does "without using any String or other class method" mean?

Your tutor probably means
StringBuffer.reverse() and StringBuilder.reverse()
but we don't know that.

Are you allowed to use
String.charAt() and StringBuffer.append()
or
String.toCharArray() and the String(char[]) constructor
or any combination of the above?
 
D

Daniel Pitts

Amit said:
for example i have string

String temp = "Java";

and I need some sort of code which reverse this string without using
any String or other class method
First: In Java, Strings are immutable. You cannot reverse a String.
Second: We will not do your homework. Tell us what you have tried so
far, and we'll gladly give you suggestion on why it doesn't work. This
is a relatively straight forward task. We've already passed this
homework assignment, now its your turn.
 
M

Malinbeg

Amit said:
How can I reverse a given string without using String or StringBuffer
class method.



String reverse (String in)
throws IOException
{
Reader reader = new StringReader(in);

Stack<Character> stack = new Stack();

int ch;

while ((ch = reader.read()) != -1)
{
stack.push((char)ch);
}


Writer writer = new StringWriter();

while (!stack.isEmpty())
{
writer.write(stack.pop());
}


String reversed = writer.toString();

return reversed;
}
 
L

Lew

Malinbeg said:
String reverse (String in)
throws IOException

To the OP:
This is an example, bear in mind. In Real Life trap and log exceptions at the
point of occurrence, then perform a strategic recovery (possibly to exit the
app?).
{
Reader reader = new StringReader(in);

Note the good use of an interface variable type with a concrete implementation
run-time type. This is a best practice.
Stack<Character> stack = new Stack();

Oops. "new Stack said:

The scope of "ch" is too wide. Put it into a for loop.
while ((ch = reader.read()) != -1)
{
stack.push((char)ch);
}


Writer writer = new StringWriter();

This one cannot go into a for loop because the value is needed after the loop.
while (!stack.isEmpty())
{
writer.write(stack.pop());
}


String reversed = writer.toString();

return reversed;
}

There are ways that follow this pattern without using java.io, also.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top