0

Possible Duplicate:
Printing reverse of any String without using any predefined function?

Please advise how to reverse a string without using built in methods. I want to use only string class, please advise let say there is a string "john is a boy" and print "yob a si nhoj".

Community
  • 1
  • 1
user1380194
  • 49
  • 1
  • 5

2 Answers2

0

This method will return the string backwards. all you have to do is iterate through the string backwards and add it to another string.

you do this using a for loop, but first check if the string has a greater lenght than 0.

Java Strings have a method "charAt(index)" which return a single character on the position of the string, where position 0 is the first character. so if you would like to reverse "Boy" you would start on letter 2, then 1, and then 0, and add them all together into a new String, resulting in "yoB".

public static String reverseString(String inString) {
    String resultString = "";//This is the resulting string, it is empty but we will add things in the next for loop
    if(inString.length()>0) {//Check the string for a lenght greater than 0
        //here we set a number to the strings lenght-1 because we start counting at 0
        //and go down to 0 and add the character at that position in the original string to the resulting one
        for(int stringCharIndex=inString.length()-1;stringCharIndex>=0;stringCharIndex--) {
            resultString+=inString.charAt(stringCharIndex);
        }
    }
    //finaly return the resulting string.
    return resultString;
}
Basilio German
  • 1,801
  • 1
  • 13
  • 22
0

You could iterate through all the characters in your string and prepend them to a StringBuffer using the insert(0, char) method. Then at the end of the iteration, your StringBuffer will be the reversed string.

mprivat
  • 21,582
  • 4
  • 54
  • 64