lastIndexOf

    1. /**
    2. * Code shared by String and StringBuffer to do searches. The
    3. * source is the character array being searched, and the target
    4. * is the string being searched for.
    5. *
    6. * @param source the characters being searched.
    7. * @param sourceOffset offset of the source string.
    8. * @param sourceCount count of the source string.
    9. * @param target the characters being searched for.
    10. * @param targetOffset offset of the target string.
    11. * @param targetCount count of the target string.
    12. * @param fromIndex the index to begin searching from.
    13. */
    14. static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
    15. char[] target, int targetOffset, int targetCount,
    16. int fromIndex) {
    17. /*
    18. * Check arguments; return immediately where possible. For
    19. * consistency, don't check for null str.
    20. */
    21. int rightIndex = sourceCount - targetCount;
    22. if (fromIndex < 0) {
    23. return -1;
    24. }
    25. if (fromIndex > rightIndex) {
    26. fromIndex = rightIndex;
    27. }
    28. /* Empty string always matches. */
    29. if (targetCount == 0) {
    30. return fromIndex;
    31. }
    32. int strLastIndex = targetOffset + targetCount - 1;
    33. char strLastChar = target[strLastIndex];
    34. int min = sourceOffset + targetCount - 1;
    35. int i = min + fromIndex;
    36. startSearchForLastChar:
    37. while (true) {
    38. while (i >= min && source[i] != strLastChar) {
    39. i--;
    40. }
    41. if (i < min) {
    42. return -1;
    43. }
    44. int j = i - 1;
    45. int start = j - (targetCount - 1);
    46. int k = strLastIndex - 1;
    47. while (j > start) {
    48. if (source[j--] != target[k--]) {
    49. i--;
    50. continue startSearchForLastChar;
    51. }
    52. }
    53. return start - sourceOffset + 1;
    54. }
    55. }