That's it, today I finally finished String 1. They were three very complicated problems, especially the last one. The first two together took me about 30 minutes, but eventually I understood them but the very last problem I just couldn't seem to solve by myself, so I requested Mr. Daly's help and we solved it together.
After finishing String, I went on to Array (on which I already begun, if you remember, but I left it early to finish strings). I had many problems left to do and I had kind of forgotten how to do Arrays and how to solve problems with them, so I did a few with Mr. Daly. I think what I find will help me with Arrays is drawing it out. Especially arrays, which have numerical values assigned in certain places - to draw everything out would help me with the problem.
Anyways, since we won't be seeing strings for a while, I figured we would do one last String problem, the last and very complex one:
Given a string, if one or both of the first 2 chars is 'x', return the string without those 'x' chars, and otherwise return the string unchanged. This is a little harder than it looks.
withoutX2("xHi") → "Hi"
withoutX2("Hxi") → "Hi"
withoutX2("Hi") → "Hi"
-------------------------------------------------------------------------------------------------------
public String withoutX2(String str) {
if (str.length()==0)
{
return "";
// if there's no character's, there can't be any x's so return an empty string.
}
if (str.length()==1 && str.substring(0,1).equals("x"))
{
return "";
// if there is only one character and that char is x, then we want to get rid of it so return an
// empty string.
}
if (str.length()==1 && !str.substring(0,1).equals("x"))
{
return str;
// if there's only one char and it's not x, then we don't want to get rid of it so just return the
// original string.
}
String theEnd = str.substring(2);
// we define a temporary string, which is the string from the 3rd character until the end.
if ((str.substring(0,2).equals("xx")))
{
return theEnd;
// if the first two chars are x, then get rid of those and return the string from the 3rd char on.
}
if (str.substring(0,1).equals("x"))
{
return str.substring(1);
// if the first char of the string is x, then return the string from the first char on.
}
if (str.substring(1,2).equals("x"))
{
return str.substring(0,1) + theEnd;
// if the second char of the string is x, then return the first char of the string + theEnd, which is
// the string from the 3rd char on.
}
return str;
// if the string does not fit any of the conditions above, then just return the original string.
}
---------------------------------------------------------------------------------------------------------
Onwards to Arrays! I will be sitting next to Preston from now on because he also is working on Array 1 and we would be able to help each other.
No comments:
Post a Comment