JAVA: comparing a String with a SubString

JAVA: comparing a String with a SubString

Should be pretty simple:

public static boolean substringWithGaps(String source, String target) {
    int targetIndex = 0;
    for (int i = 0; i < source.length(); i++) {
        if (source.charAt(i) == target.charAt(targetIndex)) {
            targetIndex = targetIndex + 1;
            if (targetIndex == target.length()) {
                return true;
            }
        }
    }
    return false;
}

We keep an index of the next letter we need to find within target. Then we loop over source looking for that letter, and when we find it we move the index within target forward one. If the index of target ever equals the length of target, that means we found all of the characters we needed. If we loop over all of source without finding all of target, we return false.

The following should do it.

public static boolean containsWithGaps(String a, String b){
    if(b.length() > a.length())
    {
      return false;
    }
    char[] targetChars = new char[b.length()];
    b.getChars(0,b.length(),targetChars, 0);
    int pos = 0;
    for(char myChar : targetChars)
    {
      pos = a.indexOf(myChar, pos);
      if(pos == -1)
      {
        return false;
      }
    }
    return true;
  }

JAVA: comparing a String with a SubString

Slight optimization in that it returns as soon as a character could not be matched (and doesnt crash if target is zero length)

public static boolean substringWithGaps(String source, String target) {
    for (int i = 0, last = -1; i < target.length(); i++) {
        if (-1 == (last = source.indexOf(target.charAt(i), last + 1)))
            return false;
    }
    return true;
}

Leave a Reply

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