Java/Data Type/String Compare

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

A string can be compared with a StringBuffer

   <source lang="java">
    

public class Main {

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

}



 </source>
   
  
 
  



Check order of two strings

   <source lang="java">
    

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
   }
 }

}



 </source>
   
  
 
  



Check order of two strings ignoring case

   <source lang="java">
    

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"); 
   }
 }

}



 </source>
   
  
 
  



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

   <source lang="java">
   

/*

* 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 {

 /**
*

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

  *
*

For example, * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7

  *
*
   * 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
   * 
  *
  * @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;
 }

}



 </source>
   
  
 
  



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

   <source lang="java">
   

/*

* 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 {


 /**
*

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

  *
*

For example, * getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "

  *
*
   * 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 "
   * 
  *
  * @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);
     }
 }  
 /**
*

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

  *
*

For example, * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7

  *
*
   * 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
   * 
  *
  * @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;
 }

}



 </source>
   
  
 
  



Compare Strings

   <source lang="java">
    

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

  • /



 </source>
   
  
 
  



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

   <source lang="java">
   

/*

* 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 {

 /**
*

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

  *
*

For example, * indexOfDifference("i am a machine", "i am a robot") -> 7

  *
*
   * 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
   * 
  *
  * @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;
 }

}



 </source>
   
  
 
  



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

   <source lang="java">
   

/*

* 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
 //-----------------------------------------------------------------------
 /**
*

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.)

  *
*

For example, * difference("i am a machine", "i am a robot") -> "robot".

  *
*
   * 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"
   * 
  *
  * @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);
 }
 /**
*

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

  *
*

For example, * indexOfDifference("i am a machine", "i am a robot") -> 7

  *
*
   * 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
   * 
  *
  * @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;
 }

}



 </source>
   
  
 
  



Compares two Strings, returning true if they are equal.

   <source lang="java">
   

/**

* 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.
*/


/**

*

Operations on {@link java.lang.String} that are * null safe.

*
* @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
 //-----------------------------------------------------------------------
 /**
*

Compares two Strings, returning true if they are equal.

  *
*

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case sensitive.

  *
*
   * 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
   * 
  *
  * @see java.lang.String#equals(Object)
  * @param str1  the first String, may be null
  * @param str2  the second String, may be null
  * @return true if the Strings are equal, case sensitive, or
  *  both null
  */
 public static boolean equals(String str1, String str2) {
     return str1 == null ? str2 == null : str1.equals(str2);
 }

}



 </source>
   
  
 
  



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

   <source lang="java">
   

/**

* 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.
*/


/**

*

Operations on {@link java.lang.String} that are * null safe.

*
* @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 {

 /**
*

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

  *
*

nulls are handled without exceptions. Two null * references are considered equal. Comparison is case insensitive.

  *
*
   * 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
   * 
  *
  * @see java.lang.String#equalsIgnoreCase(String)
  * @param str1  the first String, may be null
  * @param str2  the second String, may be null
  * @return true if the Strings are equal, case insensitive, or
  *  both null
  */
 public static boolean equalsIgnoreCase(String str1, String str2) {
     return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
 }

}



 </source>
   
  
 
  



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

   <source lang="java">
  

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.
*
**********************************************************************************/

/**

*

* StringUtil collects together some string utility classes. *

*/

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;
 }

}


 </source>
   
  
 
  



Comparing Strings

   <source lang="java">
    

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
 }

}



 </source>
   
  
 
  



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

   <source lang="java">
   

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;
 }

}



 </source>
   
  
 
  



Compute Levenshtein distance

   <source lang="java">
  

/* 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];
 }

}


 </source>
   
  
 
  



count Occurrences

   <source lang="java">
  

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;
 }

}


 </source>
   
  
 
  



Find the Levenshtein distance between two Strings.

   <source lang="java">
   

/*

* 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
 //-----------------------------------------------------------------------
 /**
*

Find the Levenshtein distance between two Strings.

  *
*

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).

  *
*

The previous implementation of the Levenshtein distance algorithm * was from

  *
*
   * 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
   * 
  *
  * @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 null
  */
 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];
 }

}



 </source>
   
  
 
  



How to compare String instances

   <source lang="java">
     

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);
 }

}



 </source>
   
  
 
  



String.compareTo

   <source lang="java">
     

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);
   }
 }

}



 </source>