Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

String Reverse

Thread view: 
Amit Jain - 08 Oct 2007 20:19 GMT
How can I reverse a given string without using String or StringBuffer
class method.
Lasse Reichstein Nielsen - 08 Oct 2007 20:31 GMT
> 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
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

Mike  Schilling - 09 Oct 2007 01:35 GMT
>> How can I reverse a given string without using String or StringBuffer
>> class method.
>
> 1. Why would you?

Because it's on his homework, of course.
Roedy Green - 09 Oct 2007 04:11 GMT
>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
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Daniel Pitts - 10 Oct 2007 06:04 GMT
> 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.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Piotr Kobzda - 10 Oct 2007 11:06 GMT
>> How can I reverse a given string without using String or StringBuffer
>> class method.
>>
> 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
Piotr Kobzda - 10 Oct 2007 11:10 GMT
> ... Thus, one should even try to do
> that!

NO-ONE of course!  :-)

piotr
Piotr Kobzda - 10 Oct 2007 10:52 GMT
> How can I reverse a given string without using String or StringBuffer
> class method.

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

piotr
Roedy Green - 10 Oct 2007 12:37 GMT
>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.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Walter Milner - 10 Oct 2007 15:05 GMT
On 10 Oct, 12:37, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:

> >new StringBuilder( givenString ).reverse().toString();
>
[quoted text clipped - 5 lines]
> Roedy Green Canadian Mind Products
> The Java Glossaryhttp://mindprod.com

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
Chris Dollin - 10 Oct 2007 15:21 GMT
> 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.)

Signature

Chris "Ivanova, one day on" Dollin

Hewlett-Packard Limited                                          registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN          690597 England

Piotr Kobzda - 10 Oct 2007 15:41 GMT
> 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
lord.zoltar@gmail.com - 10 Oct 2007 17:33 GMT
On Oct 10, 7:37 am, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:

> >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.

...Then he should make them do it in C.
Mike  Schilling - 10 Oct 2007 19:52 GMT
>> How can I reverse a given string without using String or StringBuffer
>> class method.
>
> new StringBuilder( givenString ).reverse().toString();

The Javadoc says that this handles surrogate pairs correctly, making it an
excellent answer.
Amit Jain - 11 Oct 2007 09:43 GMT
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
Thomas Schodt - 11 Oct 2007 10:50 GMT
> 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?
Daniel Pitts - 11 Oct 2007 15:08 GMT
> 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.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Stefan Ram - 10 Oct 2007 15:35 GMT
>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.)
Malinbeg - 12 Oct 2007 10:22 GMT
> 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;
}
Lew - 12 Oct 2007 14:32 GMT
> 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<Character>()".

>     int ch;

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())
>     {
[quoted text clipped - 5 lines]
>     return reversed;
> }

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

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.