I have an assignment that requires me to replace all character 'e' with the character '%'.
I'm not allowed to use any other classes like StringBuilder, StringBuffer, and I can't use Arrays or replace() methods.
This is my code:
public String replace(String s, char letter)
{
String myString = "";
String myWords = "";
for (int i = 0; i < s.length(); i ){
if (s.charAt(i) != ' ' && s.charAt(i) != letter) {
myString = myString s.charAt(i);
} else {
if (s.charAt(i) == letter){
myWords = '%';
}
myWords = myString " ";
myString = "";
}
}
return myWords;
}
This is my code so far but it's not giving me the correct output.
Input: Always eating apples
My Output: always %ating %
Correct Output: always %ating appl%s
Any help would be appreciated :) Let me know if you want me to clarify anything in particular sorry if its not clear
CodePudding user response:
Not sure why you are complicating using myWords
public static String replace(String s, char letter)
{
String myString = "";
for (int i = 0; i < s.length(); i ){
if (s.charAt(i) != letter) {
myString = myString s.charAt(i);
} else {
if (s.charAt(i) == letter){
myString = myString '%';
}
}
}
return myString;
}