CodingBat: Java. String-2, Part I


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


For the problems in the String-2 section of CodingBat, as well as all subsequent sections, it’s often a good idea to sketch the solution before starting to program. Some of the exercises are moderately complex, given the scope of the website, which means that you could easily find yourself going down the wrong path if you just rushed in. Of course this only applies if you restrict yourself to the basic set of Java methods mentioned on CodingBat. A few of the exercises pose little challenge if you use inbuilt functions of Java that go beyond the subset that is covered by CodingBat, but doing so would completely defeat the purpose of doing the exercises. After all, the point is not to merely pass the test cases, but to practice algorithmic thinking.

All solutions were successfully tested on 17 February 2013.

doubleChar:

public String doubleChar(String str) {
	String result = "";
	for (int i = 0; i < str.length(); i++) {
		char add = str.charAt(i);
		result += "" + add + add;
	}
	return result;
}
&#91;/sourcecode&#93;

The concatenation with the empty string is necessary to avoid converting the characters into ASCII codes. It's shorter than extracting a substring of length 1. If the empty string looks too esoteric for you, then feel free to rewrite that line as "result = result + add + add;".



<b>countHi:</b>
[sourcecode language="Java" gutter="false"]
public int countHi(String str) {
	int count = 0;
	for (int i = 0; i < str.length()-1; i++)
		if (str.substring(i, i+2).equals("hi"))
			count += 1; 
	return count;
}
&#91;/sourcecode&#93;


<b>catDog:</b>
[sourcecode language="Java" gutter="false"]
public boolean catDog(String str) {
	int cats = 0;
	int dogs = 0;
	for (int i = 0; i < str.length()-2; i++) {
		if (str.substring(i, i+3).equals("cat"))
			cats += 1;
		if (str.substring(i, i+3).equals("dog"))
			dogs += 1;
	}
	return cats == dogs;
}
&#91;/sourcecode&#93;


<b>countCode:</b>
[sourcecode language="Java" gutter="false"]
public int countCode(String str) {
	int count = 0;
	for (int i = 0; i < str.length()-3; i++)
		if (str.charAt(i) == 'c' && str.charAt(i+1) == 'o' 
		&& str.charAt(i+3) == 'e')
			count++;
	return count;
}
&#91;/sourcecode&#93;

<b>endOther:</b>
[sourcecode language="Java" gutter="false"]
public boolean endOther(String a, String b) {
	a = a.toLowerCase();
	b = b.toLowerCase();
	boolean test1 = a.length() >= b.length() 
			&& a.substring(a.length() - b.length()).equals(b);
	boolean test2 = b.length() >= a.length() 
			&& b.substring(b.length() - a.length()).equals(a);
	return test1 || test2;
}

Please note that you are not supposed to use endsWith(). Therefore, if you come up with the following solution, you’ve missed the point:

public boolean endOther(String a, String b) {
	a = a.toLowerCase();
	b = b.toLowerCase();
	return a.endsWith(b) || b.endsWith(a);  
}

xyzThere:

public boolean xyzThere(String str) {
	if (str.length() >= 3) {
		if (str.substring(0,3).equals("xyz")) return true;
		for (int i = 0; i < str.length()-3; i++)
			if (str.substring(i+1, i+4).equals("xyz") && 
					str.charAt(i) != '.')
				return true;
	}
	return false;
}
&#91;/sourcecode&#93;


<b>bobThere:</b>
[sourcecode language="Java" gutter="false"]
public boolean bobThere(String str) { 
	if (str.length() >= 3)
		for (int i = 0; i < str.length() - 2; i++)  
			if (str.charAt(i) == 'b' && str.charAt(i+2) == 'b')
				return true;
	return false;
}
&#91;/sourcecode&#93;

<b>xyBalance:</b>
[sourcecode language="Java" gutter="false"]
public boolean xyBalance(String str) {
	int lastX = str.lastIndexOf("y");
	int lastY = str.lastIndexOf("x");
	if (lastX == -1 && lastY == -1) return true;
	return (lastX > lastY);
}

The method lastIndexOf() is mentioned in the CodingBat tutorials.

mixString:

public String mixString(String a, String b) {
	String res = "";
	for (int i = 0; i < Math.min(a.length(), b.length()); i++)
		res += "" + a.charAt(i) + b.charAt(i);
	if (a.length() > b.length())
		return res + a.substring(b.length());
	return res + b.substring(a.length());
}

repeatEnd:

public String repeatEnd(String str, int n) {
String res = “”;
for (int i = 0; i < n; i++) res += str.substring(str.length()-n); return res; } [/sourcecode]


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


11 thoughts on “CodingBat: Java. String-2, Part I

  1. cbrown21

    For “xyzThere”,
    Can the solution be shortened to:
    for ( int I = 0; I < str.length()-2; i++)
    if (( I == 0 || str.charAt(i-1) != '.' ) && str.substring( i, i+3 ).equals( "xyz" )) return true;
    return false;

    Reply
  2. WOJTEK

    public int countCode(String str) {
    int count=0;
    for(int i=0; i<str.length()-3; i++){
    if(str.substring(i, i+4).equals("co"+str.substring(i+2,i+3)+"e"))
    count++;
    }
    return count;
    }

    Reply
  3. Fustef

    Earlier I was able to solve this in a oneliner, w.o the need of a loop. Can’t figure out anymore.
    Return new String(new char[]).replaceAll(“\0” str);

    Reply
    1. Gregor Ulm Post author

      The purpose of the Coding Bat exercises is not to find in-built functions that do the work for you. You are supposed to figure out for yourself how to do string manipulations and other fairly low-level tasks.

      Reply
  4. Aaron VanAlstine

    String-2 > mixString.
    Line: res += “” + a.charAt(i) + b.charAt(i);

    I’m wondering why res += a.charAt(i) + b.charAt(i); doesn’t work? Variable res represents an empty string, so why do we need to add another empty string to append the two chars? Seems redundant although it works.

    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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.