CharSequence last Index Of - Java java.lang

Java examples for java.lang:CharSequence

Description

CharSequence last Index Of

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        CharSequence input = "java2s.com";
        CharSequence checkFor = "java2s.com";
        System.out.println(lastIndexOf(input, checkFor));
    }//from  w w  w  .j  a v a  2s .  c om

    public static int lastIndexOf(CharSequence input, CharSequence checkFor) {
        int ret = -1;
        int check = 0;
        while (check > -1) {
            check = indexOf(input, checkFor, check);
            if (check > -1) {
                ret = check;
            } else {
                break;
            }
        }
        return ret;
    }

    /**
     * the index of method for abstract string builders & strings wants a char
     * array, and that means that many of the CharSequence objects have to copy
     * their data into a new array. try to save some allocations, try to use
     * CharSequence.charAt() which is a really fast call for those same objects.
     * 
     * @param source
     *            the characters being searched.
     * @param sourceOffset
     *            offset of the source string.
     * @param sourceCount
     *            count of the source string.
     * @param target
     *            the characters being searched for.
     * @param targetOffset
     *            offset of the target string.
     * @param targetCount
     *            count of the target string.
     * @param fromIndex
     *            the index to begin searching from.
     * @return
     */
    static int indexOf(CharSequence source, CharSequence target,
            int fromIndex) {
        if (source.length() == 0) {
            return -1;
        }

        if (target.length() == 0) {
            return -1;
        }

        if (target.length() > source.length()) {
            return -1;
        }

        for (int i = fromIndex; i < source.length(); i++) {
            int firstMatch = 0;
            if (source.charAt(i) == target.charAt(0)) {
                firstMatch = i;
                int j = 0;
                for (j = 0; j < target.length(); j++) {
                    if (target.charAt(j) != source.charAt(i)) {
                        // go backwards and re-try
                        i = i - j;
                        break;
                    }
                    i++;
                }
                if (j == target.length()) {
                    return firstMatch;
                }
            }
        }
        return -1;
    }
}

Related Tutorials