Java/Data Type/String Compare

Материал из Java эксперт
Версия от 06:19, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A string can be compared with a StringBuffer

     
public class Main {
  public static void main(String[] argv) throws Exception {
    String s1 = "s1";
    StringBuffer sbuf = new StringBuffer("a");
    boolean b = s1.contentEquals(sbuf); 
  }
}





Check order of two strings

     
public class Main {
  public static void main(String[] argv) throws Exception {
    String s1 = "s1";
    String s2 = "s2";
    
    int i = s1.rupareTo(s2); // 32; lowercase follows uppercase
    if (i < 0) {
      // s1 precedes s2
    } else if (i > 0) {
      // s1 follows s2
    } else {
      // s1 equals s2
    }
  }
}





Check order of two strings ignoring case

     
public class Main {
  public static void main(String[] argv) throws Exception {
    String s1 = "s1", s3 = "s3";
    int i = s1.rupareToIgnoreCase(s3); // -1
    if (i < 0) {
      System.out.println("s1 precedes s3"); 
    } else if (i > 0) {
      System.out.println("s1 follows s3"); 
    } else {
      System.out.println("s1 equals s3"); 
    }
  }
}





Compares all Strings in an array and returns the index at which the Strings begin to differ.

    
/*
 * 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>Compares all Strings in an array and returns the index at which the
   * Strings begin to differ.</p>
   *
   * <p>For example,
   * <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
   *
   * <pre>
   * StringUtils.indexOfDifference(null) = -1
   * StringUtils.indexOfDifference(new String[] {}) = -1
   * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
   * StringUtils.indexOfDifference(new String[] {null, null}) = -1
   * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
   * StringUtils.indexOfDifference(new String[] {"", null}) = 0
   * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
   * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
   * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
   * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
   * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
   * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
   * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
   * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
   * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
   * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
   * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
   * </pre>
   *
   * @param strs  array of strings, entries may be null
   * @return the index where the strings begin to differ; -1 if they are all equal
   * @since 2.4
   */
  public static int indexOfDifference(String[] strs) {
      if (strs == null || strs.length <= 1) {
          return -1;
      }
      boolean anyStringNull = false;
      boolean allStringsNull = true;
      int arrayLen = strs.length;
      int shortestStrLen = Integer.MAX_VALUE;
      int longestStrLen = 0;
      // find the min and max string lengths; this avoids checking to make
      // sure we are not exceeding the length of the string each time through
      // the bottom loop.
      for (int i = 0; i < arrayLen; i++) {
          if (strs[i] == null) {
              anyStringNull = true;
              shortestStrLen = 0;
          } else {
              allStringsNull = false;
              shortestStrLen = Math.min(strs[i].length(), shortestStrLen);
              longestStrLen = Math.max(strs[i].length(), longestStrLen);
          }
      }
      // handle lists containing all nulls or all empty strings
      if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
          return -1;
      }
      // handle lists containing some nulls or some empty strings
      if (shortestStrLen == 0) {
          return 0;
      }
      // find the position with the first difference across all strings
      int firstDiff = -1;
      for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
          char comparisonChar = strs[0].charAt(stringPos);
          for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
              if (strs[arrayPos].charAt(stringPos) != comparisonChar) {
                  firstDiff = stringPos;
                  break;
              }
          }
          if (firstDiff != -1) {
              break;
          }
      }
      if (firstDiff == -1 && shortestStrLen != longestStrLen) {
          // we compared all of the characters up to the length of the
          // shortest string and didn"t find a match, but the string lengths
          // vary, so return the length of the shortest string.
          return shortestStrLen;
      }
      return firstDiff;
  }
}





Compares all Strings in an array and returns the initial sequence of characters that is common to all of them.

    
/*
 * 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>Compares all Strings in an array and returns the initial sequence of 
   * characters that is common to all of them.</p>
   *
   * <p>For example,
   * <code>getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "</code></p>
   *
   * <pre>
   * StringUtils.getCommonPrefix(null) = ""
   * StringUtils.getCommonPrefix(new String[] {}) = ""
   * StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
   * StringUtils.getCommonPrefix(new String[] {null, null}) = ""
   * StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
   * StringUtils.getCommonPrefix(new String[] {"", null}) = ""
   * StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
   * StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
   * StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
   * StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
   * StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
   * StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
   * StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
   * StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
   * StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
   * StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
   * StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
   * </pre>
   *
   * @param strs  array of String objects, entries may be null
   * @return the initial sequence of characters that are common to all Strings
   * in the array; empty String if the array is null, the elements are all null 
   * or if there is no common prefix. 
   * @since 2.4
   */
  public static String getCommonPrefix(String[] strs) {
      if (strs == null || strs.length == 0) {
          return "";
      }
      int smallestIndexOfDiff = indexOfDifference(strs);
      if (smallestIndexOfDiff == -1) {
          // all strings were identical
          if (strs[0] == null) {
              return "";
          }
          return strs[0];
      } else if (smallestIndexOfDiff == 0) {
          // there were no common initial characters
          return "";
      } else {
          // we found a common initial character sequence
          return strs[0].substring(0, smallestIndexOfDiff);
      }
  }  
  /**
   * <p>Compares all Strings in an array and returns the index at which the
   * Strings begin to differ.</p>
   *
   * <p>For example,
   * <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
   *
   * <pre>
   * StringUtils.indexOfDifference(null) = -1
   * StringUtils.indexOfDifference(new String[] {}) = -1
   * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
   * StringUtils.indexOfDifference(new String[] {null, null}) = -1
   * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
   * StringUtils.indexOfDifference(new String[] {"", null}) = 0
   * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
   * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
   * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
   * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
   * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
   * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
   * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
   * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
   * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
   * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
   * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
   * </pre>
   *
   * @param strs  array of strings, entries may be null
   * @return the index where the strings begin to differ; -1 if they are all equal
   * @since 2.4
   */
  public static int indexOfDifference(String[] strs) {
      if (strs == null || strs.length <= 1) {
          return -1;
      }
      boolean anyStringNull = false;
      boolean allStringsNull = true;
      int arrayLen = strs.length;
      int shortestStrLen = Integer.MAX_VALUE;
      int longestStrLen = 0;
      // find the min and max string lengths; this avoids checking to make
      // sure we are not exceeding the length of the string each time through
      // the bottom loop.
      for (int i = 0; i < arrayLen; i++) {
          if (strs[i] == null) {
              anyStringNull = true;
              shortestStrLen = 0;
          } else {
              allStringsNull = false;
              shortestStrLen = Math.min(strs[i].length(), shortestStrLen);
              longestStrLen = Math.max(strs[i].length(), longestStrLen);
          }
      }
      // handle lists containing all nulls or all empty strings
      if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) {
          return -1;
      }
      // handle lists containing some nulls or some empty strings
      if (shortestStrLen == 0) {
          return 0;
      }
      // find the position with the first difference across all strings
      int firstDiff = -1;
      for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
          char comparisonChar = strs[0].charAt(stringPos);
          for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
              if (strs[arrayPos].charAt(stringPos) != comparisonChar) {
                  firstDiff = stringPos;
                  break;
              }
          }
          if (firstDiff != -1) {
              break;
          }
      }
      if (firstDiff == -1 && shortestStrLen != longestStrLen) {
          // we compared all of the characters up to the length of the
          // shortest string and didn"t find a match, but the string lengths
          // vary, so return the length of the shortest string.
          return shortestStrLen;
      }
      return firstDiff;
  }
}





Compare Strings

     
public class Main {
  public static void main(String[] args) {
    String str1 = new String("JAVA");
    String str2 = new String("java");
    System.out.println(str1.equals("JAVA"));
    System.out.println(str1.equals(str2));
    System.out.println(str1.equalsIgnoreCase(str2));
  }
}
/*
true
false
true
*/





Compares two Strings, and returns the index at which the Strings begin to differ.

    
/*
 * 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>Compares two Strings, and returns the index at which the
   * Strings begin to differ.</p>
   *
   * <p>For example,
   * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
   *
   * <pre>
   * StringUtils.indexOfDifference(null, null) = -1
   * StringUtils.indexOfDifference("", "") = -1
   * StringUtils.indexOfDifference("", "abc") = 0
   * StringUtils.indexOfDifference("abc", "") = 0
   * StringUtils.indexOfDifference("abc", "abc") = -1
   * StringUtils.indexOfDifference("ab", "abxyz") = 2
   * StringUtils.indexOfDifference("abcde", "abxyz") = 2
   * StringUtils.indexOfDifference("abcde", "xyz") = 0
   * </pre>
   *
   * @param str1  the first String, may be null
   * @param str2  the second String, may be null
   * @return the index where str2 and str1 begin to differ; -1 if they are equal
   * @since 2.0
   */
  public static int indexOfDifference(String str1, String str2) {
      if (str1 == str2) {
          return -1;
      }
      if (str1 == null || str2 == null) {
          return 0;
      }
      int i;
      for (i = 0; i < str1.length() && i < str2.length(); ++i) {
          if (str1.charAt(i) != str2.charAt(i)) {
              break;
          }
      }
      if (i < str2.length() || i < str1.length()) {
          return i;
      }
      return -1;
  }
}





Compares two Strings, and returns the portion where they differ.

    
/*
 * 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 {
  // Difference
  //-----------------------------------------------------------------------
  /**
   * <p>Compares two Strings, and returns the portion where they differ.
   * (More precisely, return the remainder of the second String,
   * starting from where it"s different from the first.)</p>
   *
   * <p>For example,
   * <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p>
   *
   * <pre>
   * StringUtils.difference(null, null) = null
   * StringUtils.difference("", "") = ""
   * StringUtils.difference("", "abc") = "abc"
   * StringUtils.difference("abc", "") = ""
   * StringUtils.difference("abc", "abc") = ""
   * StringUtils.difference("ab", "abxyz") = "xyz"
   * StringUtils.difference("abcde", "abxyz") = "xyz"
   * StringUtils.difference("abcde", "xyz") = "xyz"
   * </pre>
   *
   * @param str1  the first String, may be null
   * @param str2  the second String, may be null
   * @return the portion of str2 where it differs from str1; returns the
   * empty String if they are equal
   * @since 2.0
   */
  public static String difference(String str1, String str2) {
      if (str1 == null) {
          return str2;
      }
      if (str2 == null) {
          return str1;
      }
      int at = indexOfDifference(str1, str2);
      if (at == -1) {
          return "";
      }
      return str2.substring(at);
  }
  /**
   * <p>Compares two Strings, and returns the index at which the
   * Strings begin to differ.</p>
   *
   * <p>For example,
   * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
   *
   * <pre>
   * StringUtils.indexOfDifference(null, null) = -1
   * StringUtils.indexOfDifference("", "") = -1
   * StringUtils.indexOfDifference("", "abc") = 0
   * StringUtils.indexOfDifference("abc", "") = 0
   * StringUtils.indexOfDifference("abc", "abc") = -1
   * StringUtils.indexOfDifference("ab", "abxyz") = 2
   * StringUtils.indexOfDifference("abcde", "abxyz") = 2
   * StringUtils.indexOfDifference("abcde", "xyz") = 0
   * </pre>
   *
   * @param str1  the first String, may be null
   * @param str2  the second String, may be null
   * @return the index where str2 and str1 begin to differ; -1 if they are equal
   * @since 2.0
   */
  public static int indexOfDifference(String str1, String str2) {
      if (str1 == str2) {
          return -1;
      }
      if (str1 == null || str2 == null) {
          return 0;
      }
      int i;
      for (i = 0; i < str1.length() && i < str2.length(); ++i) {
          if (str1.charAt(i) != str2.charAt(i)) {
              break;
          }
      }
      if (i < str2.length() || i < str1.length()) {
          return i;
      }
      return -1;
  }
}





Compares two Strings, returning true if they are equal.

    

/**
 * 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 {
  // Equals
  //-----------------------------------------------------------------------
  /**
   * <p>Compares two Strings, returning <code>true</code> if they are equal.</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.equals(null, null)   = true
   * StringUtils.equals(null, "abc")  = false
   * StringUtils.equals("abc", null)  = false
   * StringUtils.equals("abc", "abc") = true
   * StringUtils.equals("abc", "ABC") = false
   * </pre>
   *
   * @see java.lang.String#equals(Object)
   * @param str1  the first String, may be null
   * @param str2  the second String, may be null
   * @return <code>true</code> if the Strings are equal, case sensitive, or
   *  both <code>null</code>
   */
  public static boolean equals(String str1, String str2) {
      return str1 == null ? str2 == null : str1.equals(str2);
  }
}





Compares two Strings, returning true if they are equal ignoring the case.

    

/**
 * 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>Compares two Strings, returning <code>true</code> if they are equal ignoring
   * the case.</p>
   *
   * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
   * references are considered equal. Comparison is case insensitive.</p>
   *
   * <pre>
   * StringUtils.equalsIgnoreCase(null, null)   = true
   * StringUtils.equalsIgnoreCase(null, "abc")  = false
   * StringUtils.equalsIgnoreCase("abc", null)  = false
   * StringUtils.equalsIgnoreCase("abc", "abc") = true
   * StringUtils.equalsIgnoreCase("abc", "ABC") = true
   * </pre>
   *
   * @see java.lang.String#equalsIgnoreCase(String)
   * @param str1  the first String, may be null
   * @param str2  the second String, may be null
   * @return <code>true</code> if the Strings are equal, case insensitive, or
   *  both <code>null</code>
   */
  public static boolean equalsIgnoreCase(String str1, String str2) {
      return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
  }
}





Compare two String[] for differences, either may be null

   
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
{

  /**
   * Compare two String[] for differences, either may be null
   * 
   * @param a
   *        One String[].
   * @param b
   *        The other String[].
   * @return true if the String[]s are different, false if they are the same.
   */
  public static boolean different(String[] a, String[] b)
  {
    // if both null, they are the same
    if ((a == null) && (b == null)) return false;
    // if either are null (they both are not), they are different
    if ((a == null) || (b == null)) return true;
    // if the lengths are different, they are different
    if (a.length != b.length) return true;
    // now we know neither are null, so compare, item for item (order counts)
    for (int i = 0; i < a.length; i++)
    {
      if (!a[i].equals(b[i])) return true;
    }
    // they are NOT different!
    return false;
  }
}





Comparing Strings

     
public class Main {
  public static void main(String[] argv) throws Exception {
    String s1 = "a";
    String s2 = "A";
    String s3 = "B";
    // Check if identical
    boolean b = s1.equals(s2); // false
    // Check if identical ignoring case
    b = s1.equalsIgnoreCase(s2); // true
  }
}





Compress 2 adjacent (single or double) quotes into a single (s or d) quote when found in the middle of a String.

    
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   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 {


  /**
   * Compress 2 adjacent (single or double) quotes into a single (s or d)
   * quote when found in the middle of a String.
   *
   * NOTE:  """" or """" will be compressed into "" or "".
   * This function assumes that the leading and trailing quote from a
   * string or delimited identifier have already been removed.
   * @param source string to be compressed
   * @param quotes string containing two single or double quotes.
   * @return String where quotes have been compressed
   */
  public static String compressQuotes(String source, String quotes)
  {
    String  result = source;
    int   index;
    /* Find the first occurrence of adjacent quotes. */
    index = result.indexOf(quotes);
    /* Replace each occurrence with a single quote and begin the
     * search for the next occurrence from where we left off.
     */
    while (index != -1) {
      result = result.substring(0, index + 1) +
           result.substring(index + 2);
      index = result.indexOf(quotes, index + 1);
    }
    return result;
  }
}





Compute Levenshtein distance

   
/*   Copyright 2004 The Apache Software Foundation
 *
 *   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.
 */
//based on Apache technology http://www.apache.org
public class Levenshtein {
  // ****************************
  // Get minimum of three values
  // ****************************
  private static int minimum(int a, int b, int c) {
    int mi = a;
    if (b < mi)
      mi = b;
    if (c < mi)
      mi = c;
    return mi;
  }
  // *****************************
  // Compute Levenshtein distance
  // *****************************
  public static int distance(String s, String t) {
    int d[][]; // matrix
    int n; // length of s
    int m; // length of t
    int i; // iterates through s
    int j; // iterates through t
    char s_i; // ith character of s
    char t_j; // jth character of t
    int cost; // cost
    // Step 1
    n = s.length();
    m = t.length();
    if (n == 0)
      return m;
    if (m == 0)
      return n;
    d = new int[n + 1][m + 1];
    // Step 2
    for (i = 0; i <= n; i++)
      d[i][0] = i;
    for (j = 0; j <= m; j++)
      d[0][j] = j;
    // Step 3
    for (i = 1; i <= n; i++) {
      s_i = s.charAt(i - 1);
      // Step 4
      for (j = 1; j <= m; j++) {
        t_j = t.charAt(j - 1);
        // Step 5
        if (s_i == t_j)
          cost = 0;
        else
          cost = 1;
        // Step 6
        d[i][j] = minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
      }
    }
    // Step 7
    return d[n][m];
  }
}





count Occurrences

   
public class Utils {
  public static int countOccurrences(String text, String value) {
    int i = 0;
    if ((text != null) && (value != null)) {
      //int previous = 0;
      int current = text.indexOf(value);
      while (current > -1) {
        i++;
        current += value.length();
        //previous = current;
        current = text.indexOf(value, current);
      }
    }
    return i;
  }
}





Find the Levenshtein distance between two Strings.

    
/*
 * 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 {
  
  // Misc
  //-----------------------------------------------------------------------
  /**
   * <p>Find the Levenshtein distance between two Strings.</p>
   *
   * <p>This is the number of changes needed to change one String into
   * another, where each change is a single character modification (deletion,
   * insertion or substitution).</p>
   *
   * <p>The previous implementation of the Levenshtein distance algorithm
   * was from </p>
   *
   * <pre>
   * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
   * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
   * StringUtils.getLevenshteinDistance("","")               = 0
   * StringUtils.getLevenshteinDistance("","a")              = 1
   * StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
   * StringUtils.getLevenshteinDistance("frog", "fog")       = 1
   * StringUtils.getLevenshteinDistance("fly", "ant")        = 3
   * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
   * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
   * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
   * StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
   * </pre>
   *
   * @param s  the first String, must not be null
   * @param t  the second String, must not be null
   * @return result distance
   * @throws IllegalArgumentException if either String input <code>null</code>
   */
  public static int getLevenshteinDistance(String s, String t) {
      if (s == null || t == null) {
          throw new IllegalArgumentException("Strings must not be null");
      }
      /*
         The difference between this impl. and the previous is that, rather 
         than creating and retaining a matrix of size s.length()+1 by t.length()+1, 
         we maintain two single-dimensional arrays of length s.length()+1.  The first, d,
         is the "current working" distance array that maintains the newest distance cost
         counts as we iterate through the characters of String s.  Each time we increment
         the index of String t we are comparing, d is copied to p, the second int[].  Doing so
         allows us to retain the previous cost counts as required by the algorithm (taking 
         the minimum of the cost count to the left, up one, and diagonally up and to the left
         of the current cost count being calculated).  (Note that the arrays aren"t really 
         copied anymore, just switched...this is clearly much better than cloning an array 
         or doing a System.arraycopy() each time  through the outer loop.)
         Effectively, the difference between the two implementations is this one does not 
         cause an out of memory condition when calculating the LD over two very large strings.
       */
      int n = s.length(); // length of s
      int m = t.length(); // length of t
      if (n == 0) {
          return m;
      } else if (m == 0) {
          return n;
      }
      if (n > m) {
          // swap the input strings to consume less memory
          String tmp = s;
          s = t;
          t = tmp;
          n = m;
          m = t.length();
      }
      int p[] = new int[n+1]; //"previous" cost array, horizontally
      int d[] = new int[n+1]; // cost array, horizontally
      int _d[]; //placeholder to assist in swapping p and d
      // indexes into strings s and t
      int i; // iterates through s
      int j; // iterates through t
      char t_j; // jth character of t
      int cost; // cost
      for (i = 0; i<=n; i++) {
          p[i] = i;
      }
      for (j = 1; j<=m; j++) {
          t_j = t.charAt(j-1);
          d[0] = j;
          for (i=1; i<=n; i++) {
              cost = s.charAt(i-1)==t_j ? 0 : 1;
              // minimum of cell to the left+1, to the top+1, diagonally left and up +cost
              d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1),  p[i-1]+cost);
          }
          // copy current distance counts to "previous row" distance counts
          _d = p;
          p = d;
          d = _d;
      }
      // our last action in the above loop was to switch d and p, so p now 
      // actually has the most recent cost counts
      return p[n];
  }

}





How to compare String instances

      
class MainClass {
  public static void main(String[] args) {
    String s1 = "abc";
    String s2 = "abc";
    String s3 = "def";
    if (s1 == s2)
      System.out.println("s1 == s2");
    if (s1 != s3)
      System.out.println("s1 != s3");
    if (s2 != s3)
      System.out.println("s2 != s3");
    String s4 = s1.toUpperCase();
    if (s4 != s1)
      System.out.println("s4 != s1");
    System.out.println("s1 = " + s1);
    System.out.println("s4 = " + s4);
  }
}





String.compareTo

      
public class SequenceStrings {
  public static void main(String[] args) {
    String string1 = "A";
    String string2 = "To";
    String string3 = "Z";
    String string1Out = "\"" + string1 + "\""; // string1 with quotes
    String string2Out = "\"" + string2 + "\""; // string2 with quotes
    String string3Out = "\"" + string3 + "\""; // string3 with quotes
    if (string1.rupareTo(string3) < 0)
      System.out.println(string1Out + " is less than " + string3Out);
    else {
      if (string1.rupareTo(string3) > 0)
        System.out.println(string1Out + " is greater than " + string3Out);
      else
        System.out.println(string1Out + " is equal to " + string3Out);
    }
    if (string2.rupareTo(string1) < 0)
      System.out.println(string2Out + " is less than " + string1Out);
    else {
      if (string2.rupareTo(string1) > 0)
        System.out.println(string2Out + " is greater than " + string1Out);
      else
        System.out.println(string2Out + " is equal to " + string1Out);
    }
  }
}