-1

I am trying to reverse words in a String in Java. It is initialliy passed as a char array. The way I tried is to convert it into a String array, make the change, and convert it back to a char array. However, changes are not made to the original array that is passed in as an argument, even if I tried to refer the new array to the original one. How do I handle this situation when we have to make modifications to the argument without returning anything in the function? Thanks.

public static void main(String[] args) {
    char[] s = new char[] {'t','h','e',' ','s','k','y',' ','i','s',' ','b','l','u','e'};
    reverseWords(s);
    System.out.println(s);
}

public static void reverseWords(char[] s) {
    String str = new String(s);
    String [] strArray = str.split(" ");

    int n = strArray.length;
    int begin;
    int end;
    int mid = (n-1)/2;

    for (int i=0; i<=mid; i++) {
        begin = i;
        end = (n-1) -i;
        String temp = strArray[begin];
        strArray[begin] = strArray[end];
        strArray[end] = temp;   
    }
    String s_temp =  Arrays.toString(strArray).replace("[", "").replace("]", "").replace(",", "");
    s = s_temp.toCharArray();
    System.out.println(s);
}
Mia
  • 1

1 Answers1

0

You can't do s = ....

But, you can insert the characters into the existing s array and the caller will see the changed values.

Replace this:

s = s_temp.toCharArray();

with:

for(int i = 0; i < s_temp.length(); i++) {
    s[i] = s_temp.charAt(i);
}

or use System.arraycopy().

Jason
  • 11,744
  • 3
  • 42
  • 46
  • Thanks! It works! but I am wondering why `s = s_temp.toCharArray();` wouldn't work? – Mia Apr 16 '19 at 02:01
  • Because you are setting your local variable `s` to reference the array returned by `toCharArray()`, the variable in the code that called the method won't also be changed - it will still reference the original array. So, you need to change the data in the original array instead. – Jason Apr 16 '19 at 05:57