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. - Java java.lang

Java examples for java.lang:CharSequence

Description

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.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        CharSequence source = "java2s.com";
        CharSequence target = "java2s.com";
        int fromIndex = 2;
        System.out.println(indexOf(source, target, fromIndex));
    }//  w w  w  . ja va 2 s  .  c o  m

    /**
     * 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