java – Can't change a character with .charAt ()?

Question:

I want to make a java program to replace spaces with % 20 . I was thinking of doing a loop and when I find a " " replace the character with all three characters. However I have a problem with .charAt() . Indeed it seems that you cannot change a character. Here is the error:

replaceSpaces.java:8: error: unexpected type
                s.charAt(i)="%20";
                        ^
  required: variable
  found:    value

Here is the entire program:

public class replaceSpaces{
    String s = "Hello Antoine";
    public static void replaceSpaces(String s){
        for(int i = 0;i<s.length();i++){
            if(s.charAt(i)==' '){
                s.charAt(i)="%20";
            }
        }
    System.out.println(s);
    }
}

Answer:

string.charAt returns a new instance of the character that is in the indicated position so you cannot edit that character in the string.

Try using the string.replace() method to replace all characters equal to the first parameter:

public static void replaceSpaces(String s){
       s = s.replace(" ", "%20");
       System.out.println(s);
}
replaceSpaces("Hello Antoine"); // imprime Hello%20Antoine

Keep in mind that String is immutable so it will always return a new instance, so you will have to return the result instead of assigning it to the variable s if you want to get the string with the spaces replaced:

 public static string replaceSpaces(String s){
     return s.replace(" ", "%20");
 }
 String texto = replaceSpaces("Hello Antonie");
 System.out.println(texto);// Hello%20Antonie
Scroll to Top