Skip to content

Instantly share code, notes, and snippets.

@HeGanjie
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HeGanjie/e041aa8cce918f815816 to your computer and use it in GitHub Desktop.
Save HeGanjie/e041aa8cce918f815816 to your computer and use it in GitHub Desktop.

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