Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String index out of range: -1 error with loops

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;
}
like image 400
jessca Avatar asked Dec 13 '25 16:12

jessca


1 Answers

You have a number of problems in your code.

  • You only need one StringBuilder version, that of second
  • The calls to toCharArray() are superfluous
  • You should not search for each character of first in second but in the mutable version of it sb2.
  • You are using indexOf wrong. This method should be called on the StringBuilder object to search for the first argument, you have it swapped.

The pseudocode that you can use is

isSuperAnagram(String first, String second) {
    sb = StringBuilder(second)
    for all chars in first {
        k = search index of current char of first in sb
        if(k == -1) // char is not in sb
            return false
        else
            remove char at index k from sb
    }
    return true
}
like image 137
halex Avatar answered Dec 15 '25 06:12

halex