CodingBat: Java. String-1, Part II

left2:

public String left2(String str) {
		return str.substring(2) + str.substring(0, 2);
}

right2:

public String right2(String str) {
		int len = str.length();
		return str.substring(len - 2) + str.substring(0, len - 2);
}

theEnd:

public String theEnd(String str, boolean front) {
		if (front) return str.substring(0, 1);
		return str.substring(str.length() - 1);
}

withouEnd2:

public String withouEnd2(String str) {
		if (str.length() <= 2) return "";
		return str.substring(1, str.length() - 1);
}

middleTwo:

public String middleTwo(String str) {
		int len = str.length();
		return str.substring(len / 2 - 1, len / 2 + 1);
}

endsLy:

public boolean endsLy(String str) {
		int len = str.length();
		if (len < 2) return false;
		return (str.substring(len - 2).equals("ly"));
}

nTwice:

public String nTwice(String str, int n) {
		return str.substring(0, n) + str.substring(str.length() - n);
}

twoChar:

public String twoChar(String str, int index) {
		if (index < 0 || index + 2 > str.length())
			return str.substring(0, 2);
		return str.substring(index, index + 2);
}

middleThree:

public String middleThree(String str) {
		int len = str.length();
		if (len == 3) return str;
		return str.substring(len / 2 - 1, len / 2 + 2);
}

hasBad:

public boolean hasBad(String str) {
		if (str.length() <= 2) return false;
		if (str.length() == 3) return str.substring(0, 3).equals("bad");
		return str.substring(0, 3).equals("bad")
				|| str.substring(1, 4).equals("bad");
}

3 thoughts on “CodingBat: Java. String-1, Part II

  1. Brett Campbell

    the answer you have for middletwo does not work but you are not off by much the right is
    int len = str.length();
    return str.substring(len / 2-1 , len / 2 + 2);

    Reply
  2. Ryan

    Very simple solution for the hasBad puzzle in String-1

    public boolean hasBad(String str) {
    return (str.indexOf(“bad”) == 0 || str.indexOf(“bad”) == 1);
    }

    Might be slightly ahead of the skill level required for this puzzle, but it sure is a tidy solution.

    Reply
    1. Gregor Ulm Post author

      You are not supposed to use the method indexOf(). Keep in mind that those problems are about teaching students elementary building blocks in order to prepare them for situations in which they cannot simply access a library function.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.