Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reverse String with using String class methods?

 
Skanda Raman
Ranch Hand
Posts: 205
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have a String called "Hello World". I want to reverse the same with out using any method in String Class.

Please let me know how can i do this.

 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This sounds like a homework question.

Pages that may help you:
Do your own homework.
We aren't a CodeMill
Showing Some Effort Helps a lot


That said, assuming that you actually have a java.lang.String, then it is impossible to reverse the String without using at least 1 String method. Or at least, one method from some other core Java class (like StringBuffer, or StringReader, etc...) which would call String methods.
 
Rob Spoor
Sheriff
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can cheat using the StringBuilder class, but that's not what you want

You can't do this without calling any method of String. That's because it's internals are not accessible without methods. Therefore, there is a minimum of one method to call to make those internals accessible. That method is toCharArray(). You may also want to check out a combination of length() and charAt(int) - those allow you to do the same but without creating a new char[] (which toCharArray() does).
 
Fred Hamilton
Ranch Hand
Posts: 684
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This sounds like an introductory exercise in recursive programming that I once had. By using length() and charAt(int) as Rob suggested, you can sort of simulate a situation where you are getting characters one at a time. I think this is still in the spirit of the question. Just make sure you read the string from the beginning, and don't use an array or another string to store the characters in reverse.

The following link may be useful for you.

http://erwnerve.tripod.com/prog/recursion/recintro.htm

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic