Created
July 6, 2018 12:52
-
-
Save bramses/5d9348b50d426da8d43d6f1b569cad35 to your computer and use it in GitHub Desktop.
Java Implementation of indexOf()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int indexOf(int ch, int fromIndex) { | |
if (fromIndex < 0) { | |
fromIndex = 0; | |
} else if (fromIndex >= count) { | |
// Note: fromIndex might be near -1>>>1. | |
return -1; | |
} | |
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { | |
// handle most cases here (ch is a BMP code point or a | |
// negative value (invalid code point)) | |
final char[] value = this.value; | |
final int offset = this.offset; | |
final int max = offset + count; | |
for (int i = offset + fromIndex; i < max ; i++) { | |
if (value[i] == ch) { | |
return i - offset; | |
} | |
} | |
return -1; | |
} else { | |
return indexOfSupplementary(ch, fromIndex); | |
} | |
} | |
/** | |
* Handles (rare) calls of indexOf with a supplementary character. | |
*/ | |
private int indexOfSupplementary(int ch, int fromIndex) { | |
if (Character.isValidCodePoint(ch)) { | |
final char[] value = this.value; | |
final int offset = this.offset; | |
final char hi = Character.highSurrogate(ch); | |
final char lo = Character.lowSurrogate(ch); | |
final int max = offset + count - 1; | |
for (int i = offset + fromIndex; i < max; i++) { | |
if (value[i] == hi && value[i+1] == lo) { | |
return i - offset; | |
} | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment