I am working through the Coding Bat exercises for Java. Here is one I have just completed:
Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.
And here is my solution:
public String plusOut(String str, String word){
String s = "";
String n = str + " ";
int i = 0;
while(i < str.length()) {
if (!(n.substring(i, i + word.length()).equals(word))) {
s += "+";
i++;
} else {
s += word;
i += word.length();
}
}
return s;
}
As you can see, I concatenated two spaces on the original string and used that to test the substrings. This was to avoid out of bounds exceptions.
What I want to do is optimise my solution, because I don't like how I added two spaces just to avoid errors. I want to change the if
statement so that it tests the substrings of str
rather than n
, and get rid of n
entirely. I have tried but I can't seem to find a way of doing it. How can I do this? What else needs optimising?