First problem: your loop variable ranges across all valid character indices within the value. But within the loop, you try to access characters at index
i+1
and
i+2
. If, for example, your string ends with "Jacob", you will get an exception trying to access a character past the end of the string.
Second problem: you write out either a
'*'
or a
' '
for everything in the string
apart from "bad", and then write out the remaining "bad"s at the end. If, for example, your input was
"This is very bad; your teacher forbade you from doing this.", you would output:
"**** ** *** ; **** ******* **** *** **** ***** *****badbad", which is clearly wrong.
Except you wouldn't, because of the
third problem: as soon as you find "bad", you throw away the rest of the string. So that input would actually produce,
"**** ** **** bad".
Except that's
still not quite right, because of the
fourth problem: you're writing out a
'*'
for everything that isn't a space. So when you find your first "bad", you write out a
'*'
, terminate the loop, and the write out "bad".
Stop and think what you're trying to do. Stop modifying the input string, and write out "bad" as part of the loop.
It's your homework assignment, so no code; but you want to implement something like this:
- If the current character is a space, write a space;
- Otherwise, if the current character is "b", and the index is at least three less than the length, and the next two characters are "a" and "d", write "bad";
- Otherwise, write "*";