I want to make a java program to replace spaces with % 20
. I was thinking of making a loop and when I find a " "
replacement the character with the three characters. However I have a problem with .charAt()
. Indeed 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 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);
}
}
string.charAt
returns a new instance of the character that is in the indicated position so you can't edit that character in the string.Try using the method
string.replace()
to replace all characters equal to the first parameter:Note that it
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 variables
if you want to get the string with the spaces replaced:You should do it with the method of the String object:
In this case it replaces the matches of "a" with "b".
In your case it would be:
The method you are looking for is
replace
, which searches a string for the letter and replaces it with another. Your code would look like this:Departure:
For more information the official documentation here: