Checks if some a string stands at particular point in another string - Java java.lang

Java examples for java.lang:String Index

Description

Checks if some a string stands at particular point in another string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        CharSequence hay = "java2s.com";
        CharSequence needle = "o";
        int startInd = 2;
        System.out.println(isStringAt(hay, needle, startInd));
    }//from  w ww  . ja  v a2s.  c  om

    /**
     * Checks if some string ('needle') stands at particular point ('startInd') in
     * another string ('hay').
     *
     * @param hay           String to look for 'needle' in
     * @param needle        String to check for appearance in 'hay'
     * @param startInd      Index in 'hay' at which 'needle' should stand
     * @return              <code>true</code> if 'needle' stands in 'hay' at position
     *                      'startInd'. <code>false</code> otherwise.
     */
    public static boolean isStringAt(CharSequence hay, CharSequence needle,
            int startInd) {
        boolean res = false;
        if (hay.length() >= startInd + needle.length()) {
            res = true;
            for (int i = 0, j = startInd; needle.length() > i; ++i, ++j) {
                if (hay.charAt(j) != needle.charAt(i)) {
                    res = false;
                    break;
                }
            }
        }
        return res;
    }
}

Related Tutorials