Can not change a character with .charAt ()?

10

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

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

Here is the whole 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);
    }
}
    
asked by ThePassenger 30.04.2018 в 16:37
source

3 answers

11

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

Try using the method string.replace() to replace all the 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'll 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
    
answered by 30.04.2018 / 16:47
source
2

You should do it with the object method String:

  

replaceAll ("a", "b")

In this case, replace the matches of "a" with "b".

In your case it would be:

public static void replaceSpaces(String s){
    String s = "Hello Antoine";
    String res = ""; 
    res = s.replaceAll(" ", "%20"); // remplaza espacios por %20
    System.out.println(res); // "Hello%20Antoine"
}
    
answered by 30.04.2018 в 16:47
2

The method you are looking for is replace , which searches the letter for a string and replaces it for another. Your code would be as follows:

String s = "Hello Antoine";
System.out.println(s);
//Primer parámetro letra a buscar y segundo parámetro letra a reemplazar
String replace = s.replaceAll(" ", "%20");
System.out.println(replace);

Exit:

Hello Antoine
Hello%20Antoine

For more information, the official documentation here:

  

link

    
answered by 30.04.2018 в 16:48