Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Java/Android case insensitive contains and indexOf
O(n), no Object creating, no GC, should be faster than Pattern.CASE_INSENSITIVE?

public static boolean equalsIgnoreCaseInString(String longer, int ai, String shorter, int bi) {
	int chkLen = shorter.length() - bi;
	if (longer.length() - ai < chkLen) return false;
	for (int c = 0; c < chkLen; ai++, bi++, c++) {
		char ac = longer.charAt(ai);
		char bc = shorter.charAt(bi);
		if (ac == bc
			|| ac == Character.toUpperCase(bc)
			|| ac == Character.toLowerCase(bc)) {
			continue;
		} else {
			return false;
		}
	}
	return true;
}

public static int indexOfIgnoreCase(String longer, int skip, String shorter) {
	char chInShorter = shorter.charAt(0);
	int indexOf = longer.indexOf(chInShorter, skip);
	if (indexOf == -1 && Character.isAlphabetic(chInShorter)) {
		char switchCaseHead = Character.isLowerCase(chInShorter)
				? Character.toUpperCase(chInShorter)
				: Character.toLowerCase(chInShorter);
		indexOf = longer.indexOf(switchCaseHead, skip);
	}
	
	if (indexOf == -1) return -1;
	if (equalsIgnoreCaseInString(longer, indexOf, shorter, 0)) {
		return indexOf;
	} else {
		return indexOfIgnoreCase(longer, skip + shorter.length(), shorter);
	}
}

public static boolean containsIgnoreCase(String longer, String shorter) {
	return -1 != indexOfIgnoreCase(longer, 0, shorter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment