how to reverse a string using java
how to reverse a string in java
Page 1 of 17 Replies - 4554 Views - Last Post: 24 October 2009 - 02:25 AM
Replies To: how to reverse a string in java
#2
Re: how to reverse a string in java
Posted 22 October 2009 - 07:44 PM
Use a stack to push the character onto the stack. Then pop the characters off one by one.
#3
Re: how to reverse a string in java
Posted 22 October 2009 - 08:36 PM
Or put the String into a StringBuffer which has a reverse() method
http://java.sun.com/...ringBuffer.html
http://java.sun.com/...ringBuffer.html
#4
Re: how to reverse a string in java
Posted 22 October 2009 - 10:31 PM
or just read the string and make a for loop, using the for loop you will iterate through the string backwards
This is probably more around the level of code your looking for... Good luck, if you need things explained just ask
String s =;//"User's input"
for(int i = s.length()-1; i > 0; i--) {
System.out.print(s.charAt(i));
}
This is probably more around the level of code your looking for... Good luck, if you need things explained just ask
#6
Re: how to reverse a string in java
Posted 23 October 2009 - 07:36 PM
virgul, on 22 Oct, 2009 - 09:31 PM, said:
or just read the string and make a for loop, using the for loop you will iterate through the string backwards
This is probably more around the level of code your looking for... Good luck, if you need things explained just ask
String s =;//"User's input"
for(int i = s.length()-1; i > 0; i--) {
System.out.print(s.charAt(i));
}
This is probably more around the level of code your looking for... Good luck, if you need things explained just ask
I tried the program, I got some errors.,I think I went wrong in declaration........Can you please send the complete program........I just want to compare and rectify my mistakes
#7
Re: how to reverse a string in java
Posted 24 October 2009 - 01:40 AM
Here is an example of how you can use StringBuffer to reverse a string
@virgul: Your code does not read the last character of the string. You need to use i >= 0 instead of i > 0.
String myString = "HELLO"; //Input StringBuffer sb = new StringBuffer(myString); String reverse = sb.reverse().toString(); System.out.println(reverse);
@virgul: Your code does not read the last character of the string. You need to use i >= 0 instead of i > 0.
for(int i = myString.length()-1; i >= 0; i--) {
#8
Re: how to reverse a string in java
Posted 24 October 2009 - 02:25 AM
I agree with virgul.
Another thing you could do is convert the string to a character array and then use a for loop to access each element of the array and print them out.
Good Luck!
Another thing you could do is convert the string to a character array and then use a for loop to access each element of the array and print them out.
Good Luck!
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote



|