Java tutorial
//package com.java2s; /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * Finds the index of the first word that starts with the given prefix. * <p> * If not found, returns -1. * * @param text the text in which to search for the prefix * @param prefix the text to find, in upper case letters */ public static int indexOfWordPrefix(CharSequence text, String prefix) { if (prefix == null || text == null) { return -1; } int textLength = text.length(); int prefixLength = prefix.length(); if (prefixLength == 0 || textLength < prefixLength) { return -1; } int i = 0; while (i < textLength) { // Skip non-word characters while (i < textLength && !Character.isLetterOrDigit(text.charAt(i))) { i++; } if (i + prefixLength > textLength) { return -1; } // Compare the prefixes int j; for (j = 0; j < prefixLength; j++) { if (Character.toUpperCase(text.charAt(i + j)) != prefix.charAt(j)) { break; } } if (j == prefixLength) { return i; } // Skip this word while (i < textLength && Character.isLetterOrDigit(text.charAt(i))) { i++; } } return -1; } }