That was the one out of two problems that I worked on during class. I completed another one. I now only have two problems left in String 2.
Here it is:
----------------------------------------------------------------------------------------------------------------------------------
Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad". starOut("ab*cd") → "ad" starOut("ab**cd") → "ad" starOut("sm*eilly") → "silly" ----------------------------------------------------------------------------------------------------------- |
public String starOut(String str) {
if ((str.length()<3) && (str.contains("*")))
{
return "";
}
// if the string length is less than two and there's a star, return an empty string because everything will
// be gone.
if (!str.contains("*"))
{
return str;
}
// if there is no star in the string, then we don't want to take anything out. return the string unmodified.
if (str.substring(0,1).equals("*"))
{
str=str.substring(2);
// if the star is at the very beginning of the string, then return only the string from two chars after the star
// onwards.
}
if (str.substring(str.length()-1).equals("*"))
{
str=str.substring(0,str.length()-2);
// if the star is at the very end of the string, return the string from the beginning until the char before one
// to the left of the star.
}
while (str.indexOf("*")!=-1)
// as long as there is still a star in the string,
{
int cutpoint = str.indexOf("*");
int cutpointend = cutpoint;
while (str.substring(cutpointend,cutpointend+1).equals("*"))
{
cutpointend ++;
// if the next char after the star is another star, then the cutpointend is incremented by one. this helps to
// find series of stars that come in two or three.
}
str=str.substring(0,cutpoint-1) + str.substring(cutpointend+1);
// return the string from the beginning until two before the first star, and from two after the last star until
// the end.
}
return str;
// return the modified string.
}
----------------------------------------------------------------------------------------------------------------------------------
We are approaching the end. It's almost the end of the year, and I am at arm's length of finishing String 2. Can't wait !!!
No comments:
Post a Comment