Codingbat Exercise

Given a String str1 and a String str2 , return true if str1 contains every character in str2 . The empty string is contained in any other String, including the empty string itself.

everyChar(“abc”, “xyz”) → false
everyChar(“abc”, “xya”) → false
everyChar(“xyzxyzbxyzxyz”, “xyzb”) → true

My code is like this but it still got some bugs :slightly_smiling_face: :
public boolean everyChar(String str1, String str2){
int a = str1.length();
int b = str2.length();
int j =0;
int count =0;
for (int i = 0; i < a && j < b ; i++ ) {
if (a >= b) {
if (str1.charAt(i) == str2.charAt(j) ) {
j++;
return true;
}
}
} return false;
}

1 Like

I suggest looking at the failing test cases and solving them manually - observe yourself carefully, study how you do it - your code should be doing the same. You may also want to execute your code manually for those test cases to observe what is being done correctly.

You can also reason about your code a bit. Your code currently returns true if a match is found, but finding one match is not sufficient to say that all match, you have to actually look at all.

1 Like

int a = str1.length();
int b = str2.length();
int j = 0 ;
int count =0;
if (a==0) {
if (b==0) {
return true;
}else {
return false;
}
} if (b==0) {
return true;
}
for (int i = 0; i < a && j < b ; i++ ) {
char c1 = str1.charAt(i);
char c2 = str2.charAt(j);
if ( a >= b ) {
if (c1==c2) {
j++;
return true;
} if (str1.contains(str2)){
return true;
}
}
}return false;
}

Here is my new code. I figure out the problem that you said but still didnt know how to fix it.

1 Like

Your instructions don’t ask whether the first string contains the second, not sure why you added that. Read the instructions super carefully.

You also added a bunch of special cases, but there aren’t any special cases - you should be checking every letter in the second string. If they are all present in the first string, then you should return true - no special cases at all are required for that.
If you wouldn’t be doing something when manually solving this, then your code shouldn’t be doing it either. Your code should be doing the same thing.

What you have isn’t something I’d call bugs. It’s more that you need to think through fully what needs to happen. Forget about code for a while, and consider the steps that should get carried out.

1 Like