-3

I am trying to write my own string reverse algorithm (I know this already exists in java but I am doing this for education). The code below is what I have so far. It outputs only half the string reversed. I have done some debugging and the reason is that it is changing stringChars2 at the same time as stringChars but I have no idea why that is happening as I am only trying to change stringChars. All help greatly appreciated.

EDIT my question was not "how to reverse a string" which has been asked before... but why my objects where changing without instruction, the answer below completely explains the problem.

public static void main(String[] args) {
    //declare variables
    Scanner input = new Scanner(System.in);
    String myString = "";
    int length = 0, index = 0, index2 = 0;

    //get input string
    System.out.print("Enter the string you want to reverse: ");
    myString = input.next();

    //find length of string
    length = myString.length()-1;
    index2 = length;

    //convert to array
    char[] stringChars = myString.toCharArray();
    char[] stringChars2 = stringChars;

    //loop through and reverse order
    while (index<length) {

        stringChars[index] = stringChars2[index2];

        index++;
        index2--;
    }

    //convert back to string
    String newString = new String(stringChars);

    //output result
    System.out.println(newString);

    //close resources
    input.close();

}
R Hamilton
  • 263
  • 2
  • 14

2 Answers2

0
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;

On the second line you are assigning stringChars2 to the same object as stringChars so basically they are one and the same and when you change the first you are changing the second as well.

Try something like this instead:

char[] stringChars = myString.toCharArray();
char[] stringChars2 = myString.toCharArray();

You can read more about it here

DobromirM
  • 2,017
  • 2
  • 20
  • 29
0

All that is not necessary. You can simply reverse a string with a for loop (in a method):

public String reverseString(String str)
{
    String output = "";
    int len = str.length();
    for(int k = 1; k <= str.length(); k++, len--)
    {
        output += str.substring(len-1,len);
    }
    return output;
}