001 package org.bukkit.util;
002
003 import java.util.Collection;
004 import org.apache.commons.lang.Validate;
005
006 public class StringUtil {
007
008 /**
009 * Copies all elements from the iterable collection of originals to the
010 * collection provided.
011 *
012 * @param token String to search for
013 * @param originals An iterable collection of strings to filter.
014 * @param collection The collection to add matches to
015 * @return the collection provided that would have the elements copied
016 * into
017 * @throws UnsupportedOperationException if the collection is immutable
018 * and originals contains a string which starts with the specified
019 * search string.
020 * @throws IllegalArgumentException if any parameter is is null
021 * @throws IllegalArgumentException if originals contains a null element.
022 * <b>Note: the collection may be modified before this is thrown</b>
023 */
024 public static <T extends Collection<? super String>> T copyPartialMatches(final String token, final Iterable<String> originals, final T collection) throws UnsupportedOperationException, IllegalArgumentException {
025 Validate.notNull(token, "Search token cannot be null");
026 Validate.notNull(collection, "Collection cannot be null");
027 Validate.notNull(originals, "Originals cannot be null");
028
029 for (String string : originals) {
030 if (startsWithIgnoreCase(string, token)) {
031 collection.add(string);
032 }
033 }
034
035 return collection;
036 }
037
038 /**
039 * This method uses a region to check case-insensitive equality. This
040 * means the internal array does not need to be copied like a
041 * toLowerCase() call would.
042 *
043 * @param string String to check
044 * @param prefix Prefix of string to compare
045 * @return true if provided string starts with, ignoring case, the prefix
046 * provided
047 * @throws NullPointerException if prefix is null
048 * @throws IllegalArgumentException if string is null
049 */
050 public static boolean startsWithIgnoreCase(final String string, final String prefix) throws IllegalArgumentException, NullPointerException {
051 Validate.notNull(string, "Cannot check a null string for a match");
052 if (string.length() < prefix.length()) {
053 return false;
054 }
055 return string.regionMatches(true, 0, prefix, 0, prefix.length());
056 }
057 }