Java String Last Index Of lastIndexOf(CharSequence chars, String searched)

Here you can find the source of lastIndexOf(CharSequence chars, String searched)

Description

last Index Of

License

Open Source License

Declaration

public static int lastIndexOf(CharSequence chars, String searched) 

Method Source Code

//package com.java2s;

public class Main {
    public static int lastIndexOf(CharSequence chars, String searched) {
        return lastIndexOf(chars, searched, chars.length(), false);
    }//  www.  j a  va  2  s  . c o m

    public static int lastIndexOf(CharSequence chars, String searched, int from) {
        return lastIndexOf(chars, searched, from, false);
    }

    public static int lastIndexOf(CharSequence chars, String searched, int from, boolean ignoreCase) {
        if (from < 0) {
            return -1;
        }

        int charCount = chars.length();
        int searchedLength = searched.length();

        int rightIndex = charCount - searchedLength;
        if (from > rightIndex) {
            from = rightIndex;
        }
        if (searchedLength == 0) {
            return from;
        }

        int searchedLast = searchedLength - 1;
        char searchedLastChar = charAt(searched, searchedLast, ignoreCase);
        int min = searchedLast;
        int i = from + searchedLast;

        loop: for (;;) {
            while (i >= min && charAt(chars, i, ignoreCase) != searchedLastChar) {
                i--;
            }
            if (i < min) {
                return -1;
            }

            int j = i - 1;
            int start = j - searchedLast;
            int k = searchedLast - 1;

            while (j > start) {
                if (charAt(chars, j--, ignoreCase) != charAt(searched, k--, ignoreCase)) {
                    i--;
                    continue loop;
                }
            }

            return start + 1;
        }
    }

    private static final char charAt(String chars, int index, boolean ignoreCase) {
        return (ignoreCase ? Character.toLowerCase(chars.charAt(index)) : chars.charAt(index));
    }

    private static final char charAt(CharSequence chars, int index, boolean ignoreCase) {
        return (ignoreCase ? Character.toLowerCase(chars.charAt(index)) : chars.charAt(index));
    }
}

Related

  1. lastIndexOf(char ch, String str)
  2. lastIndexof(char chr, int pos, CharSequence str)
  3. lastIndexOf(CharSequence charSeq, char ch)
  4. lastIndexOf(CharSequence cs, int searchChar, int start)
  5. lastIndexOf(CharSequence haystack, char needle)
  6. lastIndexOf(CharSequence s, char c, int start, int end)