For example, if the input String is “Java is Great” and asked to replace the letter a with x then the output would be: “Jxvx is Great” The method takes a String and two characters and returns the modified String. Please make your own assumptions if needed, you do not need to write the main.
Ans
code:-
public static String replaceChar(String s,char a,char b){
int c=0;//number of replacements
for(int i=0;i<s.length()&&c<2;i++){
if(s.charAt(i)==a){//if char a is there replace with b
s= s.substring(0,i)+b+s.substring(i+1);
c++;//increment c
}
}
return s;
}
If any doubt ask in the comments.
Get Answers For Free
Most questions answered within 1 hours.