I checked old topics with this problem and couldn't fix it.
This method is meant to compare two strings, and if every letter/character of the first string is found in the second string (not necessarily vice versa), then the method should return "true" (even if the second string has extra letters).
My idea is to check the letter at every index of the first string, see if it's in the second string, and if it is, delete that letter in both strings. When the first string runs out of letters (length equals zero) then the boolean should return true.
I think my loops or substring reaches out of range at some point.
public boolean isFound(String first, String second) {
StringBuilder sb1 = new StringBuilder(first);
StringBuilder sb2 = new StringBuilder(second);
first.toCharArray();
second.toCharArray();
for (int i = 0; i < first.length(); i++) {
int k = (first.substring(i, i + 1)).indexOf(second, i);
if (sb1.length() > 0) {
sb1.deleteCharAt(k);
sb2.deleteCharAt(k);
}
}
if (sb1.length() == 0) {
return true;
} else {
return false;
}
}
Ex: "at" and "tack" should return true, "tree" and "ere" should return false.
EDIT After reviewing the comments, my new code is now this. It always returns false, though even with "tree" and "tree".
public boolean isFound(String first, String second){
StringBuilder sb2 = new StringBuilder(second);
for(int i=0;i<first.length();i++){
int k = sb2.indexOf(first,i);
if (k==-1)
return false;
else sb2.deleteCharAt(k);
}
return true;
}