Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Issue with reversing a string

 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rene Larsen
Ranch Hand
Posts: 1179
Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to have two variables - one that count down (x -> 0) and one counting up (0 -> x)
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this for an assignment?

John.
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just for cleaner code I'd integrate j into the loop as well:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic