Return a new version of a given string where every character that comes BEFORE and AFTER a '*' are removed.
This problem is taken from CodingBat string2 module.
Example:
str: "ab*cd" returns -- "ad"
str: "sm*eilly" returns -- "silly"
Solution:
We will use 'continue' inside our if statement to solve
this problem. Our method will accept a string
and return a string that we want.
public String starOut(String givenStr) {
String newStr = "";
return newStr;
}
There are three if's statement:
1. Simply removes '*' from the given string
if(str.charAt(i)=='*') {
continue;
}
2. Starting at index greater than 0. Removes the character at current index and the previous character if that
previous character is '*'. E.g. 'ab*cd' returns 'abd'
if(i > 0 && str.charAt(i - 1) == '*') {
continue;
}
3. Loop stops at string length minus 1. Removes the character at current index and the next character if that
character happens to be a '*'.
if(i < str.length() - 1 && str.charAt(i + 1) == '*') {
continue;
}
newStr only store characters that are not covered by the
three if statements. That is the power of 'continue'.
Putting all together, we have:
public String starOut(String str) {
String newStr = "";
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='*') {
continue;
}
if(i > 0 && str.charAt(i - 1) == '*') {
continue;
}
if(i < str.length() - 1 && str.charAt(i + 1) == '*') {
continue;
}
newStr += newStr.charAt(i);
}
return newStr;
}