0

I thought arrays are passed by reference - so when I pass str into replaceSpaces, the method returns 'Mr%20John%20Smith' as a char array which is right, but when it returns back to the main method, the char array goes back to its original value of "Mr John Smith ".

public static char[] replaceSpaces(char[] s, int n) {
        String result = "";

        for(int i=0; i<n; i++) {
            if(s[i]==' ') {
                result+="%20";
            }
            else {
                result+=s[i];
            }
        }

        s=result.toCharArray();


        return s;
    }

    public static int findLastCharacter(char[] str) {
        for (int i = str.length - 1; i >= 0; i--) {
            if (str[i] != ' ') {
                return i;
            }
        }
        return -1;
    }


    public static void main(String[] args) {

        String str = "Mr John Smith    ";
        char[] arr = str.toCharArray();
        int trueLength = findLastCharacter(arr) + 1;
        replaceSpaces(arr, trueLength); 
        System.out.println("\"" + AssortedMethods.charArrayToString(arr) + "\"");


    }
  • 2
    `char[] replaceSpaces(char[] s, int n)` returns a char array - why not use it? – Scary Wombat Feb 19 '20 at 04:18
  • To explain why your code is not working as you expect it to: You never change the items within the array. Instead, you change the parameter's reference which will, of course, have no effect on the object passed into the method. – Hovercraft Full Of Eels Feb 19 '20 at 04:19
  • Use an IDE, it would tell you that the return value is ignored from replaceSpaces(arr, trueLength); and help you find the problem. – CausingUnderflowsEverywhere Feb 19 '20 at 04:20
  • You're using replaceSpaces(arr, trueLength); as a void method when you've declared it as public static char[] replaceSpaces(char[] s, int n) returning a char[]. You need to edit replaceSpaces to be void and do work on s itself. – CausingUnderflowsEverywhere Feb 19 '20 at 04:27

0 Answers0