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) + "\"");
}