Java/Data Type/String search

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Anywhere, ignore case( regular expressions )

       
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "I am Java";
    boolean b = string.matches("(?i).*i am.*");
  }
}





Case insensitive check if a String ends with a specified suffix.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 {
  /**
   * <p>Case insensitive check if a String ends with a specified suffix.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered to be equal. The comparison is case insensitive.</p>
   *
   * <pre>
   * StringUtils.endsWithIgnoreCase(null, null)      = true
   * StringUtils.endsWithIgnoreCase(null, "abcdef")  = false
   * StringUtils.endsWithIgnoreCase("def", null)     = false
   * StringUtils.endsWithIgnoreCase("def", "abcdef") = true
   * StringUtils.endsWithIgnoreCase("def", "ABCDEF") = false
   * </pre>
   *
   * @see java.lang.String#endsWith(String)
   * @param str  the String to check, may be null
   * @param suffix the suffix to find, may be null
   * @return <code>true</code> if the String ends with the suffix, case insensitive, or
   *  both <code>null</code>
   * @since 2.4
   */
  public static boolean endsWithIgnoreCase(String str, String suffix) {
      return endsWith(str, suffix, true);
  }
  /**
   * <p>Check if a String ends with a specified suffix (optionally case insensitive).</p>
   *
   * @see java.lang.String#endsWith(String)
   * @param str  the String to check, may be null
   * @param suffix the suffix to find, may be null
   * @param ignoreCase inidicates whether the compare should ignore case
   *  (case insensitive) or not.
   * @return <code>true</code> if the String starts with the prefix or
   *  both <code>null</code>
   */
  private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
      if (str == null || suffix == null) {
          return (str == null && suffix == null);
      }
      if (suffix.length() > str.length()) {
          return false;
      }
      int strOffset = str.length() - suffix.length();
      return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Case insensitive check if a String starts with a specified prefix.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 {

  /**
   * <p>Case insensitive check if a String starts with a specified prefix.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered to be equal. The comparison is case insensitive.</p>
   *
   * <pre>
   * StringUtils.startsWithIgnoreCase(null, null)      = true
   * StringUtils.startsWithIgnoreCase(null, "abcdef")  = false
   * StringUtils.startsWithIgnoreCase("abc", null)     = false
   * StringUtils.startsWithIgnoreCase("abc", "abcdef") = true
   * StringUtils.startsWithIgnoreCase("abc", "ABCDEF") = true
   * </pre>
   *
   * @see java.lang.String#startsWith(String)
   * @param str  the String to check, may be null
   * @param prefix the prefix to find, may be null
   * @return <code>true</code> if the String starts with the prefix, case insensitive, or
   *  both <code>null</code>
   * @since 2.4
   */
  public static boolean startsWithIgnoreCase(String str, String prefix) {
      return startsWith(str, prefix, true);
  }
  /**
   * <p>Check if a String starts with a specified prefix (optionally case insensitive).</p>
   *
   * @see java.lang.String#startsWith(String)
   * @param str  the String to check, may be null
   * @param prefix the prefix to find, may be null
   * @param ignoreCase inidicates whether the compare should ignore case
   *  (case insensitive) or not.
   * @return <code>true</code> if the String starts with the prefix or
   *  both <code>null</code>
   */
  private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
      if (str == null || prefix == null) {
          return (str == null && prefix == null);
      }
      if (prefix.length() > str.length()) {
          return false;
      }
      return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Case insensitive removal of a substring if it is at the begining of a source string, otherwise returns the source string.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 {

  /**
   * <p>Case insensitive removal of a substring if it is at the begining of a source string,
   * otherwise returns the source string.</p>
   *
   * <p>A <code>null</code> source string will return <code>null</code>.
   * An empty ("") source string will return the empty string.
   * A <code>null</code> search string will return the source string.</p>
   *
   * <pre>
   * StringUtils.removeStartIgnoreCase(null, *)      = null
   * StringUtils.removeStartIgnoreCase("", *)        = ""
   * StringUtils.removeStartIgnoreCase(*, null)      = *
   * StringUtils.removeStartIgnoreCase("www.domain.ru", "www.")   = "domain.ru"
   * StringUtils.removeStartIgnoreCase("www.domain.ru", "WWW.")   = "domain.ru"
   * StringUtils.removeStartIgnoreCase("domain.ru", "www.")       = "domain.ru"
   * StringUtils.removeStartIgnoreCase("www.domain.ru", "domain") = "www.domain.ru"
   * StringUtils.removeStartIgnoreCase("abc", "")    = "abc"
   * </pre>
   *
   * @param str  the source String to search, may be null
   * @param remove  the String to search for (case insensitive) and remove, may be null
   * @return the substring with the string removed if found,
   *  <code>null</code> if null String input
   * @since 2.4
   */
  public static String removeStartIgnoreCase(String str, String remove) {
      if (isEmpty(str) || isEmpty(remove)) {
          return str;
      }
      if (startsWithIgnoreCase(str, remove)) {
          return str.substring(remove.length());
      }
      return str;
  }
  /**
   * <p>Case insensitive check if a String starts with a specified prefix.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered to be equal. The comparison is case insensitive.</p>
   *
   * <pre>
   * StringUtils.startsWithIgnoreCase(null, null)      = true
   * StringUtils.startsWithIgnoreCase(null, "abcdef")  = false
   * StringUtils.startsWithIgnoreCase("abc", null)     = false
   * StringUtils.startsWithIgnoreCase("abc", "abcdef") = true
   * StringUtils.startsWithIgnoreCase("abc", "ABCDEF") = true
   * </pre>
   *
   * @see java.lang.String#startsWith(String)
   * @param str  the String to check, may be null
   * @param prefix the prefix to find, may be null
   * @return <code>true</code> if the String starts with the prefix, case insensitive, or
   *  both <code>null</code>
   * @since 2.4
   */
  public static boolean startsWithIgnoreCase(String str, String prefix) {
      return startsWith(str, prefix, true);
  }
  /**
   * <p>Check if a String starts with a specified prefix (optionally case insensitive).</p>
   *
   * @see java.lang.String#startsWith(String)
   * @param str  the String to check, may be null
   * @param prefix the prefix to find, may be null
   * @param ignoreCase inidicates whether the compare should ignore case
   *  (case insensitive) or not.
   * @return <code>true</code> if the String starts with the prefix or
   *  both <code>null</code>
   */
  private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
      if (str == null || prefix == null) {
          return (str == null && prefix == null);
      }
      if (prefix.length() > str.length()) {
          return false;
      }
      return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Case insensitive removal of a substring if it is at the end of a source string, otherwise returns the source string.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 {
  /**
   * <p>Case insensitive removal of a substring if it is at the end of a source string,
   * otherwise returns the source string.</p>
   *
   * <p>A <code>null</code> source string will return <code>null</code>.
   * An empty ("") source string will return the empty string.
   * A <code>null</code> search string will return the source string.</p>
   *
   * <pre>
   * StringUtils.removeEnd(null, *)      = null
   * StringUtils.removeEnd("", *)        = ""
   * StringUtils.removeEnd(*, null)      = *
   * StringUtils.removeEnd("www.domain.ru", ".ru.")  = "www.domain.ru."
   * StringUtils.removeEnd("www.domain.ru", ".ru")   = "www.domain"
   * StringUtils.removeEnd("www.domain.ru", "domain") = "www.domain.ru"
   * StringUtils.removeEnd("abc", "")    = "abc"
   * </pre>
   *
   * @param str  the source String to search, may be null
   * @param remove  the String to search for (case insensitive) and remove, may be null
   * @return the substring with the string removed if found,
   *  <code>null</code> if null String input
   * @since 2.4
   */
  public static String removeEndIgnoreCase(String str, String remove) {
      if (isEmpty(str) || isEmpty(remove)) {
          return str;
      }
      if (endsWithIgnoreCase(str, remove)) {
          return str.substring(0, str.length() - remove.length());
      }
      return str;
  }
  /**
   * <p>Case insensitive check if a String ends with a specified suffix.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered to be equal. The comparison is case insensitive.</p>
   *
   * <pre>
   * StringUtils.endsWithIgnoreCase(null, null)      = true
   * StringUtils.endsWithIgnoreCase(null, "abcdef")  = false
   * StringUtils.endsWithIgnoreCase("def", null)     = false
   * StringUtils.endsWithIgnoreCase("def", "abcdef") = true
   * StringUtils.endsWithIgnoreCase("def", "ABCDEF") = false
   * </pre>
   *
   * @see java.lang.String#endsWith(String)
   * @param str  the String to check, may be null
   * @param suffix the suffix to find, may be null
   * @return <code>true</code> if the String ends with the suffix, case insensitive, or
   *  both <code>null</code>
   * @since 2.4
   */
  public static boolean endsWithIgnoreCase(String str, String suffix) {
      return endsWith(str, suffix, true);
  }
  /**
   * <p>Check if a String ends with a specified suffix (optionally case insensitive).</p>
   *
   * @see java.lang.String#endsWith(String)
   * @param str  the String to check, may be null
   * @param suffix the suffix to find, may be null
   * @param ignoreCase inidicates whether the compare should ignore case
   *  (case insensitive) or not.
   * @return <code>true</code> if the String starts with the prefix or
   *  both <code>null</code>
   */
  private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
      if (str == null || suffix == null) {
          return (str == null && suffix == null);
      }
      if (suffix.length() > str.length()) {
          return false;
      }
      int strOffset = str.length() - suffix.length();
      return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Check if a String ends with a specified suffix.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 {
  // endsWith
  //-----------------------------------------------------------------------
  /**
   * <p>Check if a String ends with a specified suffix.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered to be equal. The comparison is case sensitive.</p>
   *
   * <pre>
   * StringUtils.endsWith(null, null)      = true
   * StringUtils.endsWith(null, "abcdef")  = false
   * StringUtils.endsWith("def", null)     = false
   * StringUtils.endsWith("def", "abcdef") = true
   * StringUtils.endsWith("def", "ABCDEF") = false
   * </pre>
   *
   * @see java.lang.String#endsWith(String)
   * @param str  the String to check, may be null
   * @param suffix the suffix to find, may be null
   * @return <code>true</code> if the String ends with the suffix, case sensitive, or
   *  both <code>null</code>
   * @since 2.4
   */
  public static boolean endsWith(String str, String suffix) {
      return endsWith(str, suffix, false);
  }

  /**
   * <p>Check if a String ends with a specified suffix (optionally case insensitive).</p>
   *
   * @see java.lang.String#endsWith(String)
   * @param str  the String to check, may be null
   * @param suffix the suffix to find, may be null
   * @param ignoreCase inidicates whether the compare should ignore case
   *  (case insensitive) or not.
   * @return <code>true</code> if the String starts with the prefix or
   *  both <code>null</code>
   */
  private static boolean endsWith(String str, String suffix, boolean ignoreCase) {
      if (str == null || suffix == null) {
          return (str == null && suffix == null);
      }
      if (suffix.length() > str.length()) {
          return false;
      }
      int strOffset = str.length() - suffix.length();
      return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Check if a String starts with a specified prefix.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 {
  // startsWith
  //-----------------------------------------------------------------------
  /**
   * <p>Check if a String starts with a specified prefix.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered to be equal. The comparison is case sensitive.</p>
   *
   * <pre>
   * StringUtils.startsWith(null, null)      = true
   * StringUtils.startsWith(null, "abcdef")  = false
   * StringUtils.startsWith("abc", null)     = false
   * StringUtils.startsWith("abc", "abcdef") = true
   * StringUtils.startsWith("abc", "ABCDEF") = false
   * </pre>
   *
   * @see java.lang.String#startsWith(String)
   * @param str  the String to check, may be null
   * @param prefix the prefix to find, may be null
   * @return <code>true</code> if the String starts with the prefix, case sensitive, or
   *  both <code>null</code>
   * @since 2.4
   */
  public static boolean startsWith(String str, String prefix) {
      return startsWith(str, prefix, false);
  }

  /**
   * <p>Check if a String starts with a specified prefix (optionally case insensitive).</p>
   *
   * @see java.lang.String#startsWith(String)
   * @param str  the String to check, may be null
   * @param prefix the prefix to find, may be null
   * @param ignoreCase inidicates whether the compare should ignore case
   *  (case insensitive) or not.
   * @return <code>true</code> if the String starts with the prefix or
   *  both <code>null</code>
   */
  private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
      if (str == null || prefix == null) {
          return (str == null && prefix == null);
      }
      if (prefix.length() > str.length()) {
          return false;
      }
      return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Determine if a String is contained in a String[]

  
import java.util.Collection;
import java.util.Iterator;
/**********************************************************************************
 * $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
 * $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
 ***********************************************************************************
 *
 * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 * 
 * 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.
 *
 **********************************************************************************/

/**
 * <p>
 * StringUtil collects together some string utility classes.
 * </p>
 */
public class StringUtil
{
  /**
   * Determine if a String is contained in a String[]
   * 
   * @param stringCollection
   *        The String[] to scan
   * @param value
   *        The value to look for
   * @return true if the string was found
   */
  public static boolean contains(String[] stringCollection, String value)
  {
    if (stringCollection == null || value == null) return false;
    if ((stringCollection.length == 0) || (value.length() == 0)) return false;
    for (String s : stringCollection)
    {
      if (value.equals(s)) return true;
    }
    return false;
  }
}





Determine if a String is contained in a String Collection

  
import java.util.Collection;
import java.util.Iterator;
/**********************************************************************************
 * $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
 * $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
 ***********************************************************************************
 *
 * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 * 
 * 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.
 *
 **********************************************************************************/

/**
 * <p>
 * StringUtil collects together some string utility classes.
 * </p>
 */
public class StringUtil
{
  /**
   * Determine if a String is contained in a String Collection
   * 
   * @param stringCollection
   *        The collection of (String) to scan
   * @param value
   *        The value to look for
   * @return true if the string was found
   */
  public static boolean contains(Collection stringCollection, String value)
  {
    if (stringCollection == null || value == null) return false;
    if (value.length() == 0) return false;
    for (Iterator i = stringCollection.iterator(); i.hasNext();)
    {
      Object o = i.next();
      if (!(o instanceof String)) continue;
      if (value.equals((String) o)) return true;
    }
    return false;
  }
}





Determine if a String is contained in a String Collection, ignoring case

  
import java.util.Collection;
import java.util.Iterator;
/**********************************************************************************
 * $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
 * $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
 ***********************************************************************************
 *
 * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 * 
 * 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.
 *
 **********************************************************************************/

/**
 * <p>
 * StringUtil collects together some string utility classes.
 * </p>
 */
public class StringUtil
{
  /**
   * Determine if a String is contained in a String Collection, ignoring case
   * 
   * @param stringCollection
   *        The collection of (String) to scan
   * @param value
   *        The value to look for
   * @return true if the string was found
   */
  public static boolean containsIgnoreCase(Collection stringCollection, String value)
  {
    if (stringCollection == null || value == null) return false;
    if (value.length() == 0) return false;
    for (Iterator i = stringCollection.iterator(); i.hasNext();)
    {
      Object o = i.next();
      if (!(o instanceof String)) continue;
      if (value.equalsIgnoreCase((String) o)) return true;
    }
    return false;
  }

}





Determine if a String is contained in a String [], ignoring case

  
/**********************************************************************************
 * $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
 * $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
 ***********************************************************************************
 *
 * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 * 
 * 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.
 *
 **********************************************************************************/

/**
 * <p>
 * StringUtil collects together some string utility classes.
 * </p>
 */
public class StringUtil
{
  /**
   * Determine if a String is contained in a String [], ignoring case
   * 
   * @param stringCollection
   *        The String[] to scan
   * @param value
   *        The value to look for
   * @return true if the string was found
   */
  public static boolean containsIgnoreCase(String[] stringCollection, String value)
  {
    if (stringCollection == null || value == null) return false;
    if ((stringCollection.length == 0) || (value.length() == 0)) return false;
    for (String s : stringCollection)
    {
      if (value.equalsIgnoreCase(s)) return true;
    }
    return false;
  }

}





Determine if a String is contained in a String [], ignoring case or not as specified

  
/**********************************************************************************
 * $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
 * $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
 ***********************************************************************************
 *
 * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
 * 
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 * 
 * 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.
 *
 **********************************************************************************/

/**
 * <p>
 * StringUtil collects together some string utility classes.
 * </p>
 */
public class StringUtil
{
  /**
   * Determine if a String is contained in a String [], ignoring case or not as specified
   * 
   * @param stringCollection
   *        The String[] to scan
   * @param value
   *        The value to look for
   * @param ignoreCase
   *        if true, we will do the compare case insensitive.
   * @return true if the string was found
   */
  public static boolean contains(String[] stringCollection, String value, boolean ignoreCase)
  {
    if (stringCollection == null || value == null) return false;
    if ((stringCollection.length == 0) || (value.length() == 0)) return false;
    for (String s : stringCollection)
    {
      if (ignoreCase)
      {
        if (value.equalsIgnoreCase(s)) return true;
      }
      else
      {
        if (value.equals(s)) return true;
      }
    }
    return false;
  }
}





Determines if the specified string contains only Unicode letters or digits as defined by Character#isLetterOrDigit(char)

  
/*
 * Copyright 2005 Joe Walker
 *
 * 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.
 */
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
public class Main {
  /**
   * Determines if the specified string contains only Unicode letters or
   * digits as defined by {@link Character#isLetterOrDigit(char)}
   * @param test The string to test
   * @return true if the string is non-null, non-empty and contains only
   * characters that are unicode letters or digits
   * @see Character#isLetterOrDigit(char)
   */
  public static boolean isLetterOrDigitOrUnderline(String test)
  {
      if (test == null || test.length() == 0)
      {
          return false;
      }
      for (int i = 0; i < test.length(); i++)
      {
          if (!Character.isLetterOrDigit(test.charAt(i)) && test.charAt(i) != "_")
          {
              return false;
          }
      }
      return true;
  }
}





Determining the validity of various XML names

  
/*
 * JBoss DNA (http://www.jboss.org/dna)
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * See the AUTHORS.txt file in the distribution for a full listing of 
 * individual contributors.
 *
 * Unless otherwise indicated, all code in JBoss DNA is licensed
 * to you under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 * 
 * JBoss DNA is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
/**
 * A utility class for determining the validity of various XML names, per the 
 * .
 */
public class XmlCharacters {
    private static final int NUMBER_OF_CHARACTERS = 1 << 16; // 65536 or 0x10000
    /**
     * This implementation uses an array that captures for each character the XML classifications.
     * An array is used because it is a fast way of looking up each character.
     */
    private static final char[] MASKS = new char[NUMBER_OF_CHARACTERS];
    private static final int VALID_CHARACTER = 1;
    private static final int CONTENT_CHARACTER = 1 <<1;
    private static final int SPACE_CHARACTER = 1 <<2;
    private static final int NAME_START_CHARACTER = 1<<3;
    private static final int NAME_CHARACTER = 1<<4;
    private static final int NCNAME_START_CHARACTER = 1<<5;
    private static final int NCNAME_CHARACTER = 1<<6;
    private static final int PUBID_CHARACTER = 1<<7;
    static {
        // ----------------
        // Valid Characters
        // ----------------
        // [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
        // See http://www.w3.org/TR/REC-xml/#charsets
        MASKS[0x9] |= VALID_CHARACTER | CONTENT_CHARACTER;
        MASKS[0xA] |= VALID_CHARACTER | CONTENT_CHARACTER;
        MASKS[0xD] |= VALID_CHARACTER | CONTENT_CHARACTER;
        for (int i = 0x20; i <= 0xD7FF; ++i) MASKS[i] |= VALID_CHARACTER | CONTENT_CHARACTER;
        for (int i = 0xE000; i <= 0xFFFD; ++i) MASKS[i] |= VALID_CHARACTER | CONTENT_CHARACTER;
        // Last range is bigger than our character array, so we"ll handle in the "isValid" method  ...
        // for ( int i=0x10000; i<=0x10FFFF; ++i ) MASKS[i] = VALID_CHARACTER_MASK | CONTENT_CHARACTER;
        // Remove the other characters that are not allowed in XML content:
        // "<", "&", "\n", "\r", "]"
        MASKS["<"] &= ~(CONTENT_CHARACTER);
        MASKS["&"] &= ~(CONTENT_CHARACTER);
        MASKS["\n"] &= ~(CONTENT_CHARACTER);
        MASKS["\r"] &= ~(CONTENT_CHARACTER);
        MASKS["]"] &= ~(CONTENT_CHARACTER);
        
        // ---------------------
        // Whitespace Characters
        // ---------------------
        // [3] S ::= (#x20 | #x9 | #xD | #xA)+
        // See http://www.w3.org/TR/REC-xml/#sec-common-syn
        MASKS[0x20] |= SPACE_CHARACTER;
        MASKS[0x9] |= SPACE_CHARACTER;
        MASKS[0xA] |= SPACE_CHARACTER;
        MASKS[0xD] |= SPACE_CHARACTER;
        // ---------------------
        // Name Start Characters
        // ---------------------
        // [4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] |
        // [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] |
        // [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
        // [#x10000-#xEFFFF]
        // See http://www.w3.org/TR/REC-xml/#sec-common-syn
        //
        // Note that all these start characters AND characters are valid for NAME and NCNAME
        int nameStartMask = NAME_START_CHARACTER | NCNAME_START_CHARACTER | NAME_CHARACTER | NCNAME_CHARACTER;
        MASKS[":"] |= nameStartMask;
        MASKS["_"] |= nameStartMask;
        for (int i = "A"; i <= "Z"; ++i) MASKS[i] |= nameStartMask;
        for (int i = "a"; i <= "z"; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0xC0; i <= 0xD6; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0xD8; i <= 0xF6; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0xF8; i <= 0x2FF; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x370; i <= 0x37D; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x37F; i <= 0x1FFF; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x200C; i <= 0x200D; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x2070; i <= 0x218F; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x2C00; i <= 0x2FEF; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x3001; i <= 0xD7FF; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0xF900; i <= 0xFDCF; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0xFDF0; i <= 0xFFFD; ++i) MASKS[i] |= nameStartMask;
        // Last range is bigger than our character array ...
        //for (int i = 0x10000; i <= 0xEFFFF; ++i) MASKS[i] |= nameStartMask;
        // ---------------
        // Name Characters
        // ---------------
        // [4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
        // See http://www.w3.org/TR/REC-xml/#sec-common-syn
        //
        // Note that all these characters are valid for NAME and NCNAME
        int nameMask = NAME_CHARACTER | NCNAME_CHARACTER;
        MASKS["-"] |= nameMask;
        MASKS["."] |= nameMask;
        MASKS[0xB7] |= nameMask;
        for (int i = "0"; i <= "9"; ++i) MASKS[i] |= nameMask;
        for (int i = 0x0300; i <= 0x036F; ++i) MASKS[i] |= nameStartMask;
        for (int i = 0x203F; i <= 0x2040; ++i) MASKS[i] |= nameStartMask;
        
        // --------
        // NC Names
        // --------
        // [4] NCName ::= NCNameStartChar NCNameChar*
        // which is just an XML Name, minus the ":"
        // See http://www.w3.org/TR/REC-xml-names/#ns-decl
        // So, remove the NCNAME_CHARACTER and NCNAME_START_CHARACTER masks from ":" ...
        MASKS[":"] &= ~(NCNAME_START_CHARACTER | NCNAME_CHARACTER);
        
        // --------------------
        // Public ID characters
        // --------------------
        // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-"()+,./:=?;!*#@$_%]
        MASKS[0x20] |= PUBID_CHARACTER;
        MASKS[0xA] |= PUBID_CHARACTER;
        MASKS[0xD] |= PUBID_CHARACTER;
        for (int i = "A"; i <= "Z"; ++i) MASKS[i] |= PUBID_CHARACTER;
        for (int i = "a"; i <= "z"; ++i) MASKS[i] |= PUBID_CHARACTER;
        for (int i = "0"; i <= "9"; ++i) MASKS[i] |= PUBID_CHARACTER;
        MASKS["-"] |= PUBID_CHARACTER;
        MASKS["\""] |= PUBID_CHARACTER;
        MASKS["("] |= PUBID_CHARACTER;
        MASKS[")"] |= PUBID_CHARACTER;
        MASKS["+"] |= PUBID_CHARACTER;
        MASKS[","] |= PUBID_CHARACTER;
        MASKS["."] |= PUBID_CHARACTER;
        MASKS["/"] |= PUBID_CHARACTER;
        MASKS[":"] |= PUBID_CHARACTER;
        MASKS["="] |= PUBID_CHARACTER;
        MASKS["?"] |= PUBID_CHARACTER;
        MASKS[";"] |= PUBID_CHARACTER;
        MASKS["!"] |= PUBID_CHARACTER;
        MASKS["*"] |= PUBID_CHARACTER;
        MASKS["#"] |= PUBID_CHARACTER;
        MASKS["@"] |= PUBID_CHARACTER;
        MASKS["$"] |= PUBID_CHARACTER;
        MASKS["_"] |= PUBID_CHARACTER;
        MASKS["%"] |= PUBID_CHARACTER;
    }
    private XmlCharacters() {
    }
    /**
     * Determine whether the supplied character is a valid first character in an XML Name.
     * The first character in an XML name is more restrictive than the {@link #isValidName(int) remaining characters}.
     * 
     * @param c the character
     * @return true if the character is valid for an XML Name"s first character
     */
    public static boolean isValidNameStart( int c ) {
        return c < NUMBER_OF_CHARACTERS && ( MASKS[c] & NAME_START_CHARACTER ) != 0;
    }
    /**
     * Determine whether the supplied character is a valid first character in an XML NCName.
     * The first character in an XML NCName is more restrictive than the {@link #isValidName(int) remaining characters}.
     * 
     * @param c the character
     * @return true if the character is valid for an XML NCName"s first character
     */
    public static boolean isValidNcNameStart( int c ) {
        return c < NUMBER_OF_CHARACTERS && ( MASKS[c] & NCNAME_START_CHARACTER ) != 0;
    }
    /**
     * Determine whether the supplied character is a valid non-first character in an XML Name.
     * The {@link #isValidNameStart(int) first character} in an XML name is more restrictive than the remaining characters.
     * 
     * @param c the character
     * @return true if the character is valid character in an XML Name
     */
    public static boolean isValidName( int c ) {
        return c < NUMBER_OF_CHARACTERS && ( MASKS[c] & NAME_CHARACTER ) != 0;
    }
    /**
     * Determine whether the supplied character is a valid non-first character in an XML NCName.
     * The {@link #isValidNcNameStart(int) first character} in an XML NCName is more restrictive than the remaining characters.
     * 
     * @param c the character
     * @return true if the character is valid character in an XML NCName
     */
    public static boolean isValidNcName( int c ) {
        return c < NUMBER_OF_CHARACTERS && ( MASKS[c] & NCNAME_CHARACTER ) != 0;
    }
    /**
     * Determine whether the supplied character is a valid character in an XML Pubid.
     * 
     * @param c the character
     * @return true if the character is valid character in an XML Pubid
     */
    public static boolean isValidPubid( int c ) {
        return c < NUMBER_OF_CHARACTERS && ( MASKS[c] & PUBID_CHARACTER ) != 0;
    }
    /**
     * Determine whether the supplied character is a valid character in XML.
     * 
     * @param c the character
     * @return true if the character is valid character in XML
     */
    public static boolean isValid( int c ) {
        return (c < NUMBER_OF_CHARACTERS && ( MASKS[c] & VALID_CHARACTER ) != 0) || ( 0x10000 <= c && c <= 0x10FFFF);
    }
    /**
     * Determine whether the supplied character is a valid character in XML content
     * 
     * @param c the character
     * @return true if the character is valid character in XML content
     */
    public static boolean isValidContent( int c ) {
        return (c < NUMBER_OF_CHARACTERS && ( MASKS[c] & CONTENT_CHARACTER ) != 0) || ( 0x10000 <= c && c <= 0x10FFFF);
    }
    /**
     * Determine whether the supplied character is a valid whitespace character in XML
     * 
     * @param c the character
     * @return true if the character is valid whitespace character in XML
     */
    public static boolean isValidSpace( int c ) {
        return c <= 0x20 && ( MASKS[c] & SPACE_CHARACTER ) != 0;
    }
    
    /**
     * Determine if the supplied name is a valid XML Name.
     * 
     * @param name the string being checked
     * @return true if the supplied name is indeed a valid XML Name, or false otherwise
     */
    public static boolean isValidName( String name ) {
        if ( name == null || name.length() == 0 ) return false;
        CharacterIterator iter = new StringCharacterIterator(name);
        char c = iter.first();
        if ( !isValidNameStart(c) ) return false;
        while ( c != CharacterIterator.DONE ) {
            if ( !isValidName(c) ) return false;
            c = iter.next();
        }
        return true;
    }
    
    /**
     * Determine if the supplied name is a valid XML NCName.
     * 
     * @param name the string being checked
     * @return true if the supplied name is indeed a valid XML NCName, or false otherwise
     */
    public static boolean isValidNcName( String name ) {
        if ( name == null || name.length() == 0 ) return false;
        CharacterIterator iter = new StringCharacterIterator(name);
        char c = iter.first();
        if ( !isValidNcNameStart(c) ) return false;
        while ( c != CharacterIterator.DONE ) {
            if ( !isValidNcName(c) ) return false;
            c = iter.next();
        }
        return true;
    }
}





Ends with, ignore case( regular expressions )

       
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "I am Java";
    boolean b = string.matches("(?i).*adam");
  }
}





Finds the first index within a String, handling null.

   

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */


/**
 * <p>Operations on {@link java.lang.String} that are
 * <code>null</code> safe.</p>
 *
 * @see java.lang.String
 * @author 
 * @author Arun Mammen Thomas
 * @author Gary Gregory
 * @author Phil Steitz
 * @author Al Chou
 * @author Michael Davey
 * @author Reuben Sivan
 * @author Chris Hyzer
 * @author Scott Johnson
 * @since 1.0
 * @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
 */
public class Main {
  /**
   * <p>Finds the first index within a String, handling <code>null</code>.
   * This method uses {@link String#indexOf(String, int)}.</p>
   *
   * <p>A <code>null</code> String will return <code>-1</code>.
   * A negative start position is treated as zero.
   * An empty ("") search String always matches.
   * A start position greater than the string length only matches
   * an empty search String.</p>
   *
   * <pre>
   * StringUtils.indexOf(null, *, *)          = -1
   * StringUtils.indexOf(*, null, *)          = -1
   * StringUtils.indexOf("", "", 0)           = 0
   * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
   * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
   * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
   * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
   * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
   * StringUtils.indexOf("aabaabaa", "b", -1) = 2
   * StringUtils.indexOf("aabaabaa", "", 2)   = 2
   * StringUtils.indexOf("abc", "", 9)        = 3
   * </pre>
   *
   * @param str  the String to check, may be null
   * @param searchStr  the String to find, may be null
   * @param startPos  the start position, negative treated as zero
   * @return the first index of the search String,
   *  -1 if no match or <code>null</code> string input
   * @since 2.0
   */
  public static int indexOf(String str, String searchStr, int startPos) {
      if (str == null || searchStr == null) {
          return -1;
      }
      // JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence
      if (searchStr.length() == 0 && startPos >= str.length()) {
          return str.length();
      }
      return str.indexOf(searchStr, startPos);
  }
}





Finds the last index within a String from a start position, handling null.

   

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */


/**
 * <p>Operations on {@link java.lang.String} that are
 * <code>null</code> safe.</p>
 *
 * @see java.lang.String
 * @author 
 * @author Arun Mammen Thomas
 * @author Gary Gregory
 * @author Phil Steitz
 * @author Al Chou
 * @author Michael Davey
 * @author Reuben Sivan
 * @author Chris Hyzer
 * @author Scott Johnson
 * @since 1.0
 * @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
 */
public class Main {
  /**
   * <p>Finds the last index within a String from a start position,
   * handling <code>null</code>.
   * This method uses {@link String#lastIndexOf(int, int)}.</p>
   *
   * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
   * A negative start position returns <code>-1</code>.
   * A start position greater than the string length searches the whole string.</p>
   *
   * <pre>
   * StringUtils.lastIndexOf(null, *, *)          = -1
   * StringUtils.lastIndexOf("", *,  *)           = -1
   * StringUtils.lastIndexOf("aabaabaa", "b", 8)  = 5
   * StringUtils.lastIndexOf("aabaabaa", "b", 4)  = 2
   * StringUtils.lastIndexOf("aabaabaa", "b", 0)  = -1
   * StringUtils.lastIndexOf("aabaabaa", "b", 9)  = 5
   * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
   * StringUtils.lastIndexOf("aabaabaa", "a", 0)  = 0
   * </pre>
   *
   * @param str  the String to check, may be null
   * @param searchChar  the character to find
   * @param startPos  the start position
   * @return the last index of the search character,
   *  -1 if no match or <code>null</code> string input
   * @since 2.0
   */
  public static int lastIndexOf(String str, char searchChar, int startPos) {
      if (isEmpty(str)) {
          return -1;
      }
      return str.lastIndexOf(searchChar, startPos);
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Finds the n-th index within a String, handling null.

   

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */


/**
 * <p>Operations on {@link java.lang.String} that are
 * <code>null</code> safe.</p>
 *
 * @see java.lang.String
 * @author 
 * @author Arun Mammen Thomas
 * @author Gary Gregory
 * @author Phil Steitz
 * @author Al Chou
 * @author Michael Davey
 * @author Reuben Sivan
 * @author Chris Hyzer
 * @author Scott Johnson
 * @since 1.0
 * @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
 */
public class Main {
  /**
   * <p>Finds the n-th index within a String, handling <code>null</code>.
   * This method uses {@link String#indexOf(String)}.</p>
   *
   * <p>A <code>null</code> String will return <code>-1</code>.</p>
   *
   * <pre>
   * StringUtils.ordinalIndexOf(null, *, *)          = -1
   * StringUtils.ordinalIndexOf(*, null, *)          = -1
   * StringUtils.ordinalIndexOf("", "", *)           = 0
   * StringUtils.ordinalIndexOf("aabaabaa", "a", 1)  = 0
   * StringUtils.ordinalIndexOf("aabaabaa", "a", 2)  = 1
   * StringUtils.ordinalIndexOf("aabaabaa", "b", 1)  = 2
   * StringUtils.ordinalIndexOf("aabaabaa", "b", 2)  = 5
   * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
   * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
   * StringUtils.ordinalIndexOf("aabaabaa", "", 1)   = 0
   * StringUtils.ordinalIndexOf("aabaabaa", "", 2)   = 0
   * </pre>
   *
   * @param str  the String to check, may be null
   * @param searchStr  the String to find, may be null
   * @param ordinal  the n-th <code>searchStr</code> to find
   * @return the n-th index of the search String,
   *  <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
   * @since 2.1
   */
  public static int ordinalIndexOf(String str, String searchStr, int ordinal) {
      if (str == null || searchStr == null || ordinal <= 0) {
          return -1;
      }
      if (searchStr.length() == 0) {
          return 0;
      }
      int found = 0;
      int index = -1;
      do {
          index = str.indexOf(searchStr, index + 1);
          if (index < 0) {
              return index;
          }
          found++;
      } while (found < ordinal);
      return index;
  }

}





Helper functions to query a strings end portion. The comparison is case insensitive.

      

public class Main {
  /**
   * Helper functions to query a strings end portion. The comparison is case insensitive.
   *
   * @param base  the base string.
   * @param end  the ending text.
   *
   * @return true, if the string ends with the given ending text.
   */
  public static boolean endsWithIgnoreCase(final String base, final String end) {
      if (base.length() < end.length()) {
          return false;
      }
      return base.regionMatches(true, base.length() - end.length(), end, 0, end.length());
  }

}





Helper functions to query a strings start portion. The comparison is case insensitive.

      

public class Main {
  /**
   * Helper functions to query a strings start portion. The comparison is case insensitive.
   *
   * @param base  the base string.
   * @param start  the starting text.
   *
   * @return true, if the string starts with the given starting text.
   */
  public static boolean startsWithIgnoreCase(final String base, final String start) {
      if (base.length() < start.length()) {
          return false;
      }
      return base.regionMatches(true, 0, start, 0, start.length());
  }
}





If a string contains a specific word

       
 
public class Main {
  public static void main(String[] args) {
    String name = "Java";
    if (name.indexOf("Java") != -1) {
      System.out.println("Bravo Java!");
    } else {
      System.out.println("Can"t find Java");
    }
  }
}





if a String starts with a digit or uppercase letter

       
import java.util.regex.Pattern;
public class Main {
  public static void main(String[] argv) {
    System.out.println(startsWithDigitOrUpper("asdf1234"));
  }
  static boolean startsWithDigitOrUpper(String s) {
    return Pattern.rupile("^[A-Z0-9]").matcher(s).find();
  }
}
//false





Java Search String

       
public class Main {
  public static void main(String[] args) {
    String strOrig = "A B C A";
    int intIndex = strOrig.indexOf("B");
    if (intIndex == -1) {
      System.out.println("not found");
    } else {
      System.out.println("Found " + intIndex);
    }
    int positionIndex = strOrig.indexOf("A", 2);
    System.out.println("after 2 is " + positionIndex);
    int lastIndex = strOrig.lastIndexOf("A");
    System.out.println("Last index " + lastIndex);
  }
}
/*
Found 2
after 2 is 6
Last index 6
*/





Java String endsWith

       
public class Main {
  public static void main(String[] args) {
    String strOrig = "Hello World";
    if (strOrig.endsWith("World")) {
      System.out.println("ends with World");
    } else {
      System.out.println("not end with World");
    }
  }
}





Java String startsWith

       
public class Main {
  public static void main(String[] args) {
    String strOrig = "Hello World";
    if (strOrig.startsWith("Hello")) {
      System.out.println("String starts with Hello");
    } else {
      System.out.println("String does not start with Hello");
    }
  }
}





Look for particular sequences in sentences

       
// : c12:AnalyzeSentence.java
// Look for particular sequences in sentences.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.StringTokenizer;
public class AnalyzeSentence {
  public static void main(String[] args) {
    analyze("I am happy about this");
    analyze("I am not happy about this");
    analyze("I am not! I am happy");
    analyze("I am sad about this");
    analyze("I am not sad about this");
    analyze("I am not! I am sad");
    analyze("Are you happy about this?");
    analyze("Are you sad about this?");
    analyze("It"s you! I am happy");
    analyze("It"s you! I am sad");
  }
  private static StringTokenizer st;
  private static void analyze(String s) {
    System.out.println("\nnew sentence >> " + s);
    boolean sad = false;
    st = new StringTokenizer(s);
    while (st.hasMoreTokens()) {
      String token = next();
      // Look until you find one of the
      // two starting tokens:
      if (!token.equals("I") && !token.equals("Are"))
        continue; // Top of while loop
      if (token.equals("I")) {
        String tk2 = next();
        if (!tk2.equals("am")) // Must be after I
          break; // Out of while loop
        else {
          String tk3 = next();
          if (tk3.equals("sad")) {
            sad = true;
            break; // Out of while loop
          }
          if (tk3.equals("not")) {
            String tk4 = next();
            if (tk4.equals("sad"))
              break; // Leave sad false
            if (tk4.equals("happy")) {
              sad = true;
              break;
            }
          }
        }
      }
      if (token.equals("Are")) {
        String tk2 = next();
        if (!tk2.equals("you"))
          break; // Must be after Are
        String tk3 = next();
        if (tk3.equals("sad"))
          sad = true;
        break; // Out of while loop
      }
    }
    if (sad)
      System.out.println("Sad detected");
  }
  static String next() {
    if (st.hasMoreTokens()) {
      String s = st.nextToken();
      System.out.println(s);
      return s;
    } else
      return "";
  }
} ///:~





Not found

       
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "I am Java";
    int index = string.lastIndexOf("z"); // -1
  }
}





Not found returns -1

       
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "this is another test.";
    int index = string.lastIndexOf("z"); // -1
  }
}





Palindrome

       
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class Palindrome {
  public static boolean isPalindrome(String stringToTest) {
    String workingCopy = removeJunk(stringToTest);
    String reversedCopy = reverse(workingCopy);
    return reversedCopy.equalsIgnoreCase(workingCopy);
  }
  protected static String removeJunk(String string) {
    int i, len = string.length();
    StringBuffer dest = new StringBuffer(len);
    char c;
    for (i = (len - 1); i >= 0; i--) {
      c = string.charAt(i);
      if (Character.isLetterOrDigit(c)) {
        dest.append(c);
      }
    }
    return dest.toString();
  }
  protected static String reverse(String string) {
    StringBuffer sb = new StringBuffer(string);
    return sb.reverse().toString();
  }
  public static void main(String[] args) {
    String string = "Madam, I"m Adam.";
    System.out.println();
    System.out.println("Testing whether the following "
        + "string is a palindrome:");
    System.out.println("    " + string);
    System.out.println();
    if (isPalindrome(string)) {
      System.out.println("It IS a palindrome!");
    } else {
      System.out.println("It is NOT a palindrome!");
    }
    System.out.println();
  }
}





Returns an index into arra (or -1) where the character is not in the charset byte array.

     
/* Copyright (c) 2001-2009, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Collection of static methods for operations on arrays
 *
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 1.9.0
 * @since 1.7.2
 */
public class Main {
  /**
   * Returns an index into arra (or -1) where the character is not in the
   * charset byte array.
   */
  public static int findNotIn(byte[] arra, int start, int limit,
                              byte[] charset) {
      int k = 0;
      for (; k < limit; k++) {
          for (int i = 0; i < charset.length; i++) {
              if (arra[k] == charset[i]) {
                  continue;
              }
          }
          return k;
      }
      return -1;
  }
}





Returns an int[] array of length segments containing the distribution count of the elements in unsorted int[] array with values between min and max (range).

     
     
/* Copyright (c) 2001-2009, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Collection of routines for counting the distribution of the values
 * in an int[] array.
 *
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 1.7.2
 * @since 1.7.2
 */
public class ArrayCounter {
    /**
     * Returns an int[] array of length segments containing the distribution
     * count of the elements in unsorted int[] array with values between min
     * and max (range). Values outside the min-max range are ignored<p>
     *
     * A usage example is determining the count of people of each age group
     * in a large int[] array containing the age of each person. Called with
     * (array, 16,0,79), it will return an int[16] with the first element
     * the count of people aged 0-4, the second element the count of those
     * aged 5-9, and so on. People above the age of 79 are excluded. If the
     * range is not a multiple of segments, the last segment will be cover a
     * smaller sub-range than the rest.
     *
     */
    public static int[] countSegments(int[] array, int elements,
                                      int segments, int start, int limit) {
        int[] counts   = new int[segments];
        long  interval = calcInterval(segments, start, limit);
        int   index    = 0;
        int   element  = 0;
        if (interval <= 0) {
            return counts;
        }
        for (int i = 0; i < elements; i++) {
            element = array[i];
            if (element < start || element >= limit) {
                continue;
            }
            index = (int) ((element - start) / interval);
            counts[index]++;
        }
        return counts;
    }
    /**
     * With an unsorted int[] array and with target a positive integer in the
     * range (1,array.length), finds the value in the range (start,limit) of the
     * largest element (rank) where the count of all smaller elements in that
     * range is less than or equals target. Parameter margin indicates the
     * margin of error in target<p>
     *
     * In statistics, this can be used to calculate a median or quadrile value.
     * A usage example applied to an array of age values is to determine
     * the maximum age of a given number of people. With the example array
     * given in countSegments, rank(array, c, 6000, 18, 65, 0) will return an age
     * value between 18-64 (inclusive) and the count of all people aged between
     * 18 and the returned value(exclusive) will be less than or equal 6000.
     *
     */
    public static int rank(int[] array, int elements, int target, int start,
                           int limit, int margin) {
        final int segments     = 256;
        int       elementCount = 0;
        int       currentLimit = limit;
        for (;;) {
            long interval = calcInterval(segments, start, currentLimit);
            int[] counts = countSegments(array, elements, segments, start,
                                         currentLimit);
            for (int i = 0; i < counts.length; i++) {
                if (elementCount + counts[i] < target) {
                    elementCount += counts[i];
                    start        += interval;
                } else {
                    break;
                }
            }
            if (elementCount + margin >= target) {
                return start;
            }
            if (interval <= 1) {
                return start;
            }
            currentLimit = start + interval < limit ? (int) (start + interval)
                                                    : limit;
        }
    }
    /**
     * Helper method to calculate the span of the sub-interval. Simply returns
     * the cieling of ((limit - start) / segments) and accounts for invalid
     * start and limit combinations.
     */
    static long calcInterval(int segments, int start, int limit) {
        long range = limit - start;
        if (range < 0) {
            return 0;
        }
        int partSegment = (range % segments) == 0 ? 0
                                                  : 1;
        return (range / segments) + partSegment;
    }
}





Returns the next index of a character from the chars string

      
// 
// Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.
// 

// 
/** Fast String Utilities.
 *
 * These string utilities provide both conveniance methods and
 * performance improvements over most standard library versions. The
 * main aim of the optimizations is to avoid object creation unless
 * absolutely required.
 *
 * @author Greg Wilkins (gregw)
 */
class StringUtil
{

    /* ------------------------------------------------------------ */
    /**
     * returns the next index of a character from the chars string
     */
    public static int indexFrom(String s,String chars)
    {
        for (int i=0;i<s.length();i++)
           if (chars.indexOf(s.charAt(i))>=0)
              return i;
        return -1;
    }
    
}





Return the nth index of the given token occurring in the given string

   
import java.util.Map;

/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */

public class Main{
  /**
   * Return the <i>nth</i> index of the given token occurring in the given string.
   *
   * @param string     String to search.
   * @param token      Token to match.
   * @param index      <i>Nth</i> index.
   * @return           Index of <i>nth</i> item or -1.
   */
  public static int nthIndexOf(final String string, final String token,
     final int index)
  {
     int j = 0;
     for (int i = 0; i < index; i++)
     {
        j = string.indexOf(token, j + 1);
        if (j == -1) break;
     }
     return j;
  }
}





Search a String to find the first index of any character in the given set of characters.

      

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */


/**
 * <p>Operations on {@link java.lang.String} that are
 * <code>null</code> safe.</p>
 *
 * @see java.lang.String
 * @author 
 * @author Arun Mammen Thomas
 * @author Gary Gregory
 * @author Phil Steitz
 * @author Al Chou
 * @author Michael Davey
 * @author Reuben Sivan
 * @author Chris Hyzer
 * @author Scott Johnson
 * @since 1.0
 * @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
 */
public class Main {
  // IndexOfAny chars
  //-----------------------------------------------------------------------
  /**
   * <p>Search a String to find the first index of any
   * character in the given set of characters.</p>
   *
   * <p>A <code>null</code> String will return <code>-1</code>.
   * A <code>null</code> or zero length search array will return <code>-1</code>.</p>
   *
   * <pre>
   * StringUtils.indexOfAny(null, *)                = -1
   * StringUtils.indexOfAny("", *)                  = -1
   * StringUtils.indexOfAny(*, null)                = -1
   * StringUtils.indexOfAny(*, [])                  = -1
   * StringUtils.indexOfAny("zzabyycdxx",["z","a"]) = 0
   * StringUtils.indexOfAny("zzabyycdxx",["b","y"]) = 3
   * StringUtils.indexOfAny("aba", ["z"])           = -1
   * </pre>
   *
   * @param str  the String to check, may be null
   * @param searchChars  the chars to search for, may be null
   * @return the index of any of the chars, -1 if no match or null input
   * @since 2.0
   */
  public static int indexOfAny(String str, char[] searchChars) {
      if (isEmpty(str) || isEmpty(searchChars)) {
          return -1;
      }
      for (int i = 0; i < str.length(); i++) {
          char ch = str.charAt(i);
          for (int j = 0; j < searchChars.length; j++) {
              if (searchChars[j] == ch) {
                  return i;
              }
          }
      }
      return -1;
  }
  // ----------------------------------------------------------------------
  /**
   * <p>Checks if an array of Objects is empty or <code>null</code>.</p>
   *
   * @param array  the array to test
   * @return <code>true</code> if the array is empty or <code>null</code>
   * @since 2.1
   */
  public static boolean isEmpty(char[] array) {
      if (array == null || array.length == 0) {
          return true;
      }
      return false;
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Search a String to find the first index of any character not in the given set of characters.

      

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */


/**
 * <p>Operations on {@link java.lang.String} that are
 * <code>null</code> safe.</p>
 *
 * @see java.lang.String
 * @author 
 * @author Arun Mammen Thomas
 * @author Gary Gregory
 * @author Phil Steitz
 * @author Al Chou
 * @author Michael Davey
 * @author Reuben Sivan
 * @author Chris Hyzer
 * @author Scott Johnson
 * @since 1.0
 * @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
 */
public class Main {
  // IndexOfAnyBut chars
  //-----------------------------------------------------------------------
  /**
   * <p>Search a String to find the first index of any
   * character not in the given set of characters.</p>
   *
   * <p>A <code>null</code> String will return <code>-1</code>.
   * A <code>null</code> or zero length search array will return <code>-1</code>.</p>
   *
   * <pre>
   * StringUtils.indexOfAnyBut(null, *)           = -1
   * StringUtils.indexOfAnyBut("", *)             = -1
   * StringUtils.indexOfAnyBut(*, null)           = -1
   * StringUtils.indexOfAnyBut(*, [])             = -1
   * StringUtils.indexOfAnyBut("zzabyycdxx","za") = 3
   * StringUtils.indexOfAnyBut("zzabyycdxx", "")  = 0
   * StringUtils.indexOfAnyBut("aba", "ab")       = -1
   * </pre>
   *
   * @param str  the String to check, may be null
   * @param searchChars  the chars to search for, may be null
   * @return the index of any of the chars, -1 if no match or null input
   * @since 2.0
   */
  public static int indexOfAnyBut(String str, char[] searchChars) {
      if (isEmpty(str) || isEmpty(searchChars)) {
          return -1;
      }
      outer : for (int i = 0; i < str.length(); i++) {
          char ch = str.charAt(i);
          for (int j = 0; j < searchChars.length; j++) {
              if (searchChars[j] == ch) {
                  continue outer;
              }
          }
          return i;
      }
      return -1;
  }
  // ----------------------------------------------------------------------
  /**
   * <p>Checks if an array of Objects is empty or <code>null</code>.</p>
   *
   * @param array  the array to test
   * @return <code>true</code> if the array is empty or <code>null</code>
   * @since 2.1
   */
  public static boolean isEmpty(char[] array) {
      if (array == null || array.length == 0) {
          return true;
      }
      return false;
  }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Search a substring Anywhere

       

public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "I am Java";
    boolean b = string.indexOf("I am") > 0; // true
  }
}





Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.

      
import java.util.ArrayList;
import java.util.List;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */


/**
 * <p>Operations on {@link java.lang.String} that are
 * <code>null</code> safe.</p>
 *
 * @see java.lang.String
 * @author 
 * @author Arun Mammen Thomas
 * @author Gary Gregory
 * @author Phil Steitz
 * @author Al Chou
 * @author Michael Davey
 * @author Reuben Sivan
 * @author Chris Hyzer
 * @author Scott Johnson
 * @since 1.0
 * @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
 */
public class Main {

    /**
     * <p>Searches a String for substrings delimited by a start and end tag,
     * returning all matching substrings in an array.</p>
     *
     * <p>A <code>null</code> input String returns <code>null</code>.
     * A <code>null</code> open/close returns <code>null</code> (no match).
     * An empty ("") open/close returns <code>null</code> (no match).</p>
     *
     * <pre>
     * StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
     * StringUtils.substringsBetween(null, *, *)            = null
     * StringUtils.substringsBetween(*, null, *)            = null
     * StringUtils.substringsBetween(*, *, null)            = null
     * StringUtils.substringsBetween("", "[", "]")          = []
     * </pre>
     *
     * @param str  the String containing the substrings, null returns null, empty returns empty
     * @param open  the String identifying the start of the substring, empty returns null
     * @param close  the String identifying the end of the substring, empty returns null
     * @return a String Array of substrings, or <code>null</code> if no match
     * @since 2.3
     */
    public static String[] substringsBetween(String str, String open, String close) {
        if (str == null || isEmpty(open) || isEmpty(close)) {
            return null;
        }
        int strLen = str.length();
        if (strLen == 0) {
            return new String[0];
        }
        int closeLen = close.length();
        int openLen = open.length();
        List list = new ArrayList();
        int pos = 0;
        while (pos < (strLen - closeLen)) {
            int start = str.indexOf(open, pos);
            if (start < 0) {
                break;
            }
            start += openLen;
            int end = str.indexOf(close, start);
            if (end < 0) {
                break;
            }
            list.add(str.substring(start, end));
            pos = end + closeLen;
        }
        if (list.isEmpty()) {
            return null;
        } 
        return (String[]) list.toArray(new String [list.size()]);
    }
  // Empty checks
  //-----------------------------------------------------------------------
  /**
   * <p>Checks if a String is empty ("") or null.</p>
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>NOTE: This method changed in Lang version 2.0.
   * It no longer trims the String.
   * That functionality is available in isBlank().</p>
   *
   * @param str  the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }

}





Searching a String for a Character or a Substring

       
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "this is a test";
    int index = string.indexOf("a");
  }
}





Starts with, ignore case( regular expressions )

       
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "I am Java";
    boolean b = string.matches("(?i)i am.*");
  }
}





String Region Match Demo

       
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class RegionMatchesDemo {
    public static void main(String[] args) {
        String searchMe = "Green Eggs and Ham";
        String findMe = "Eggs";
        int len = findMe.length();
        boolean foundIt = false;
        int i = 0;
        while (!searchMe.regionMatches(i, findMe, 0, len)) {
            i++;
            foundIt = true;
        }
        if (foundIt) {
            System.out.println(searchMe.substring(i, i+len));
        }
    }
}





Strings -- extract printable strings from binary file

       
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
 * Strings -- extract printable strings from binary file
 * 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Strings.java,v 1.3 2004/02/08 23:57:29 ian Exp $
 */
public class Strings {
  protected int minLength = 4;
  /**
   * Return true if the character is printable IN ASCII. Not using
   * Character.isLetterOrDigit(); applies to all unicode ranges
   */
  protected boolean isStringChar(char ch) {
    if (ch >= "a" && ch <= "z")
      return true;
    if (ch >= "A" && ch <= "Z")
      return true;
    if (ch >= "0" && ch <= "9")
      return true;
    switch (ch) {
    case "/":
    case "-":
    case ":":
    case ".":
    case ",":
    case "_":
    case "$":
    case "%":
    case "\"":
    case "(":
    case ")":
    case "[":
    case "]":
    case "<":
    case ">":
      return true;
    }
    return false;
  }
  /** Process one file */
  protected void process(String fileName, InputStream inStream) {
    try {
      int i;
      char ch;
      // This line alone cuts the runtime by about 66% on large files.
      BufferedInputStream is = new BufferedInputStream(inStream);
      StringBuffer sb = new StringBuffer();
      // Read a byte, cast it to char, check if part of printable string.
      while ((i = is.read()) != -1) {
        ch = (char) i;
        if (isStringChar(ch) || (sb.length() > 0 && ch == " "))
          // If so, build up string.
          sb.append(ch);
        else {
          // if not, see if anything to output.
          if (sb.length() == 0)
            continue;
          if (sb.length() >= minLength) {
            report(fileName, sb);
          }
          sb.setLength(0);
        }
      }
      is.close();
    } catch (IOException e) {
      System.out.println("IOException: " + e);
    }
  }
  /**
   * This simple main program looks after filenames and opening files and such
   * like for you.
   */
  public static void main(String[] av) {
    Strings o = new Strings();
    if (av.length == 0) {
      o.process("standard input", System.in);
    } else {
      for (int i = 0; i < av.length; i++)
        try {
          o.process(av[i], new FileInputStream(av[i]));
        } catch (FileNotFoundException e) {
          System.err.println(e);
        }
    }
  }
  /** Output a match. Made a separate method for use by subclassers. */
  protected void report(String fName, StringBuffer theString) {
    System.out.println(fName + ": " + theString);
  }
}





Wrapper for arrays of ordered strings. This verifies the arrays and supports efficient lookups.

      

/**
 * Wrapper for arrays of ordered strings. This verifies the arrays and supports
 * efficient lookups.
 * 
 * @author Dennis M. Sosnoski
 */
public class StringArray
{
    /** Ordered array of strings. */
    private final String[] m_list;
    
    /**
     * Constructor from array of values. This checks the array values to make
     * sure they"re ordered and unique, and if they"re not throws an exception.
     * Once the array has been passed to this constructor it must not be
     * modified by outside code.
     * 
     * @param list array of values
     */
    public StringArray(String[] list) {
        validateArray(list);
        m_list = list;
    }
    /**
     * Constructor from array of values to be added to base instance. This
     * merges the array values, making sure they"re ordered and unique, and if
     * they"re not throws an exception.
     * 
     * @param list array of values
     * @param base base instance
     */
    public StringArray(String[] list, StringArray base) {
        validateArray(list);
        m_list = mergeArrays(list, base.m_list);
    }
    /**
     * Constructor from pair of base instances. This merges the values, making
     * sure they"re unique, and if they"re not throws an exception.
     * 
     * @param array1 first base array
     * @param array2 second base array
     */
    public StringArray(StringArray array1, StringArray array2) {
        m_list = mergeArrays(array1.m_list, array2.m_list);
    }
    /**
     * Constructor from array of values to be added to pair of base instances.
     * This merges the array values, making sure they"re ordered and unique, and
     * if they"re not throws an exception.
     * 
     * @param list array of values
     * @param array1 first base array
     * @param array2 second base array
     */
    public StringArray(String[] list, StringArray array1, StringArray array2) {
        validateArray(list);
        m_list = mergeArrays(list, mergeArrays(array1.m_list, array2.m_list));
    }
    /**
     * Constructor from array of values to be added to three base instances.
     * This merges the array values, making sure they"re ordered and unique, and
     * if they"re not throws an exception.
     * 
     * @param list array of values
     * @param array1 first base array
     * @param array2 second base array
     * @param array3 third base array
     */
    public StringArray(String[] list, StringArray array1, StringArray array2,
        StringArray array3) {
        validateArray(list);
        m_list = mergeArrays(list, mergeArrays(array1.m_list,
            mergeArrays(array2.m_list, array3.m_list)));
    }
    /**
     * Constructor from array of values to be added to four base instances.
     * This merges the array values, making sure they"re ordered and unique, and
     * if they"re not throws an exception.
     * 
     * @param list array of values
     * @param array1 first base array
     * @param array2 second base array
     * @param array3 third base array
     * @param array4 fourth base array
     */
    public StringArray(String[] list, StringArray array1, StringArray array2,
        StringArray array3, StringArray array4) {
        validateArray(list);
        m_list = mergeArrays(list, mergeArrays(array1.m_list,
            mergeArrays(array2.m_list,
            mergeArrays(array3.m_list, array4.m_list))));
    }
    
    /**
     * Merge a pair of ordered arrays into a single array. The two source arrays
     * must not contain any values in common.
     * 
     * @param list1 first ordered array
     * @param list2 second ordered array
     * @return merged array
     */
    private String[] mergeArrays(String[] list1, String[] list2) {
        String[] merge = new String[list1.length + list2.length];
        int fill = 0;
        int i = 0;
        int j = 0;
        while (i < list1.length && j < list2.length) {
            int diff = list2[j].rupareTo(list1[i]);
            if (diff > 0) {
                merge[fill++] = list1[i++];
            } else if (diff < 0) {
                merge[fill++] = list2[j++];
            } else {
                throw new IllegalArgumentException
                    ("Repeated value not allowed: \"" + list1[i] + """);
            }
        }
        if (i < list1.length) {
            System.arraycopy(list1, i, merge, fill, list1.length-i);
        }
        if (j < list2.length) {
            System.arraycopy(list2, j, merge, fill, list2.length-j);
        }
        return merge;
    }
    /**
     * Make sure passed-in array contains values that are in order and without
     * duplicate values.
     * 
     * @param list
     */
    private void validateArray(String[] list) {
        if (list.length > 0) {
            String last = list[0];
            int index = 0;
            while (++index < list.length) {
                String comp = list[index];
                int diff = last.rupareTo(comp);
                if (diff > 0) {
                    throw new IllegalArgumentException
                        ("Array values are not ordered");
                } else if (diff < 0) {
                    last = comp;
                } else {
                    throw new IllegalArgumentException
                        ("Duplicate values in array");
                }
            }
        }
    }
    
    /**
     * Get string at a particular index in the list.
     *
     * @param index list index to be returned
     * @return string at that index position
     */
    public String get(int index) {
        return m_list[index];
    }
    
    /**
     * Find index of a particular string in the array. This does
     * a binary search through the array values, using a pair of
     * index bounds to track the subarray of possible matches at
     * each iteration.
     *
     * @param value string to be found in list
     * @return index of string in array, or <code>-1</code> if
     * not present
     */
    public int indexOf(String value) {
        int base = 0;
        int limit = m_list.length - 1;
        while (base <= limit) {
            int cur = (base + limit) >> 1;
            int diff = value.rupareTo(m_list[cur]);
            if (diff < 0) {
                limit = cur - 1;
            } else if (diff > 0) {
                base = cur + 1;
            } else {
                return cur;
            }
        }
        return -1;
    }
    
    /**
     * Get number of values in array
     *
     * @return number of values in array
     */
    public int size() {
        return m_list.length;
    }
}