File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Issue with reversing a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Issue with reversing a string " Watch "Issue with reversing a string " New topic
Author

Issue with reversing a string

Nelson Sam
Ranch Hand

Joined: Jun 12, 2010
Posts: 30
I am trying to reverse the string s1 using the below code and store it in char array named c.
But I am getting the same s1 as output instead of it being reversed.

Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

You are really close. The issue here is the index you are assigning the characters to. Add this to your for loop:


And see if you can tell what you're doing wrong.

Hunter

"If the facts don't fit the theory, get new facts" --Albert Einstein
Rene Larsen
Ranch Hand

Joined: Oct 12, 2001
Posts: 1179

You need to have two variables - one that count down (x -> 0) and one counting up (0 -> x)


Regards, Rene Larsen
Dropbox Invite
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Is this for an assignment?

John.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19543
    
  16

Rene Larsen wrote:You need to have two variables - one that count down (x -> 0) and one counting up (0 -> x)

That or use a calculation for one of the two array accesses. Like s1.length() - 1 - i. The two variables would be easier though.

Nelson, one hint: instead of using "new char[26]", use "new char[s1.length()]". That will a) allow you to use strings larger than 26 characters, and b) not take up space for 26 characters if fewer (e.g. 5) are needed.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Nelson Sam
Ranch Hand

Joined: Jun 12, 2010
Posts: 30
Thank you all for replying.

@Hunter McMillen-Thanks for pointing out where I went wrong.
@Rene Larsen-Thanks for the concept.I have implemented it in my program
@Rob Prime - Thanks for your idea too.

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19543
    
  16

Just for cleaner code I'd integrate j into the loop as well:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Issue with reversing a string
 
Similar Threads
Dereferenced Error Code
Find one char in a String ? ? ?
Doubt in an Interface Question!!
prog of multiple inputs
Using switch with a string