Java/Data Type/String substring

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

Check if String Contains another String

   <source lang="java">
   

public class Main {

 public static void main(String[] args) {
   String haystack = "this is a test";
   String needle1 = "Java";
   int index1 = haystack.indexOf(needle1);
   if (index1 != -1)
     System.out.println("The string contains the substring " + needle1);
   else
     System.out.println("The string does not contain the substring " + needle1);
 }

} //The string does not contain the substring Java



 </source>
   
  
 
  



Counts how many times the substring appears in the larger String.

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

 //-----------------------------------------------------------------------
 /**
*

Counts how many times the substring appears in the larger String.

  *
*

A null or empty ("") String input returns 0.

  *
*
   * StringUtils.countMatches(null, *)       = 0
   * StringUtils.countMatches("", *)         = 0
   * StringUtils.countMatches("abba", null)  = 0
   * StringUtils.countMatches("abba", "")    = 0
   * StringUtils.countMatches("abba", "a")   = 2
   * StringUtils.countMatches("abba", "ab")  = 1
   * StringUtils.countMatches("abba", "xxx") = 0
   * 
  *
  * @param str  the String to check, may be null
  * @param sub  the substring to count, may be null
  * @return the number of occurrences, 0 if either String is null
  */
 public static int countMatches(String str, String sub) {
     if (isEmpty(str) || isEmpty(sub)) {
         return 0;
     }
     int count = 0;
     int idx = 0;
     while ((idx = str.indexOf(sub, idx)) != -1) {
         count++;
         idx += sub.length();
     }
     return count;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Count the number of instances of substring within a string

   <source lang="java">
 

/*

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

 /////////////////////////////////////////////////////////////////////////
 //                          Counting Methods                           //
 /////////////////////////////////////////////////////////////////////////
 /**
  * Count the number of instances of substring within a string.
  *
  * @param string     String to look for substring in.
  * @param substring  Sub-string to look for.
  * @return           Count of substrings in string.
  */
 public static int count(final String string, final String substring)
 {
    int count = 0;
    int idx = 0;
    while ((idx = string.indexOf(substring, idx)) != -1)
    {
       idx++;
       count++;
    }
    return count;
 }
 /**
  * Count the number of instances of character within a string.
  *
  * @param string     String to look for substring in.
  * @param c          Character to look for.
  * @return           Count of substrings in string.
  */
 public static int count(final String string, final char c)
 {
    return count(string, String.valueOf(c));
 }

}


 </source>
   
  
 
  



Find the first index of any of a set of potential substrings.

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

 // IndexOfAny strings
 //-----------------------------------------------------------------------
 /**
*

Find the first index of any of a set of potential substrings.

  *
*

A null String will return -1. * A null or zero length search array will return -1. * A null search array entry will be ignored, but a search * array containing "" will return 0 if str is not * null. This method uses {@link String#indexOf(String)}.

  *
*
   * StringUtils.indexOfAny(null, *)                     = -1
   * StringUtils.indexOfAny(*, null)                     = -1
   * StringUtils.indexOfAny(*, [])                       = -1
   * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"])   = 2
   * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"])   = 2
   * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"])   = -1
   * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
   * StringUtils.indexOfAny("zzabyycdxx", [""])          = 0
   * StringUtils.indexOfAny("", [""])                    = 0
   * StringUtils.indexOfAny("", ["a"])                   = -1
   * 
  *
  * @param str  the String to check, may be null
  * @param searchStrs  the Strings to search for, may be null
  * @return the first index of any of the searchStrs in str, -1 if no match
  */
 public static int indexOfAny(String str, String[] searchStrs) {
     if ((str == null) || (searchStrs == null)) {
         return -1;
     }
     int sz = searchStrs.length;
     // String"s can"t have a MAX_VALUEth index.
     int ret = Integer.MAX_VALUE;
     int tmp = 0;
     for (int i = 0; i < sz; i++) {
         String search = searchStrs[i];
         if (search == null) {
             continue;
         }
         tmp = str.indexOf(search);
         if (tmp == -1) {
             continue;
         }
         if (tmp < ret) {
             ret = tmp;
         }
     }
     return (ret == Integer.MAX_VALUE) ? -1 : ret;
 }
 // ----------------------------------------------------------------------
 /**
*

Checks if an array of Objects is empty or null.

  *
  * @param array  the array to test
  * @return true if the array is empty or null
  * @since 2.1
  */
 public static boolean isEmpty(char[] array) {
     if (array == null || array.length == 0) {
         return true;
     }
     return false;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Find the latest index of any of a set of potential substrings.

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

 /**
*

Find the latest index of any of a set of potential substrings.

  *
*

A null String will return -1. * A null search array will return -1. * A null or zero length search array entry will be ignored, * but a search array containing "" will return the length of str * if str is not null. This method uses {@link String#indexOf(String)}

  *
*
   * StringUtils.lastIndexOfAny(null, *)                   = -1
   * StringUtils.lastIndexOfAny(*, null)                   = -1
   * StringUtils.lastIndexOfAny(*, [])                     = -1
   * StringUtils.lastIndexOfAny(*, [null])                 = -1
   * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
   * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
   * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
   * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
   * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""])   = 10
   * 
  *
  * @param str  the String to check, may be null
  * @param searchStrs  the Strings to search for, may be null
  * @return the last index of any of the Strings, -1 if no match
  */
 public static int lastIndexOfAny(String str, String[] searchStrs) {
     if ((str == null) || (searchStrs == null)) {
         return -1;
     }
     int sz = searchStrs.length;
     int ret = -1;
     int tmp = 0;
     for (int i = 0; i < sz; i++) {
         String search = searchStrs[i];
         if (search == null) {
             continue;
         }
         tmp = str.lastIndexOf(search);
         if (tmp > ret) {
             ret = tmp;
         }
     }
     return ret;
 }
 // ----------------------------------------------------------------------
 /**
*

Checks if an array of Objects is empty or null.

  *
  * @param array  the array to test
  * @return true if the array is empty or null
  * @since 2.1
  */
 public static boolean isEmpty(char[] array) {
     if (array == null || array.length == 0) {
         return true;
     }
     return false;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Gets a substring from the specified String avoiding exceptions

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

 // Substring
 //-----------------------------------------------------------------------
 /**
*

Gets a substring from the specified String avoiding exceptions.

  *
*

A negative start position can be used to start n * characters from the end of the String.

  *
*

A null String will return null. * An empty ("") String will return "".

  *
*
   * StringUtils.substring(null, *)   = null
   * StringUtils.substring("", *)     = ""
   * StringUtils.substring("abc", 0)  = "abc"
   * StringUtils.substring("abc", 2)  = "c"
   * StringUtils.substring("abc", 4)  = ""
   * StringUtils.substring("abc", -2) = "bc"
   * StringUtils.substring("abc", -4) = "abc"
   * 
  *
  * @param str  the String to get the substring from, may be null
  * @param start  the position to start from, negative means
  *  count back from the end of the String by this many characters
  * @return substring from start position, null if null String input
  */
 public static String substring(String str, int start) {
     if (str == null) {
         return null;
     }
     // handle negatives, which means last n characters
     if (start < 0) {
         start = str.length() + start; // remember start is negative
     }
     if (start < 0) {
         start = 0;
     }
     if (start > str.length()) {
         return "";
     }
     return str.substring(start);
 }

}


 </source>
   
  
 
  



Gets len characters from the middle of a String.

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

 /**
*

Gets len characters from the middle of a String.

  *
*

If len characters are not available, the remainder * of the String will be returned without an exception. If the * String is null, null will be returned. * An exception is thrown if len is negative.

  *
*
   * StringUtils.mid(null, *, *)    = null
   * StringUtils.mid(*, *, -ve)     = ""
   * StringUtils.mid("", 0, *)      = ""
   * StringUtils.mid("abc", 0, 2)   = "ab"
   * StringUtils.mid("abc", 0, 4)   = "abc"
   * StringUtils.mid("abc", 2, 4)   = "c"
   * StringUtils.mid("abc", 4, 2)   = ""
   * StringUtils.mid("abc", -2, 2)  = "ab"
   * 
  *
  * @param str  the String to get the characters from, may be null
  * @param pos  the position to start from, negative treated as zero
  * @param len  the length of the required String, must be zero or positive
  * @return the middle characters, null if null String input
  */
 public static String mid(String str, int pos, int len) {
     if (str == null) {
         return null;
     }
     if (len < 0 || pos > str.length()) {
         return "";
     }
     if (pos < 0) {
         pos = 0;
     }
     if (str.length() <= (pos + len)) {
         return str.substring(pos);
     }
     return str.substring(pos, pos + len);
 }

}


 </source>
   
  
 
  



Gets the String that is nested in between two instances of the same String.

   <source lang="java">
 

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


/**

*

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 {

 // Substring between
 //-----------------------------------------------------------------------
 /**
*

Gets the String that is nested in between two instances of the * same String.

  *
*

A null input String returns null. * A null tag returns null.

  *
*
   * StringUtils.substringBetween(null, *)            = null
   * StringUtils.substringBetween("", "")             = ""
   * StringUtils.substringBetween("", "tag")          = null
   * StringUtils.substringBetween("tagabctag", null)  = null
   * StringUtils.substringBetween("tagabctag", "")    = ""
   * StringUtils.substringBetween("tagabctag", "tag") = "abc"
   * 
  *
  * @param str  the String containing the substring, may be null
  * @param tag  the String before and after the substring, may be null
  * @return the substring, null if no match
  * @since 2.0
  */
 public static String substringBetween(String str, String tag) {
     return substringBetween(str, tag, tag);
 }
 /**
*

Gets the String that is nested in between two Strings. * Only the first match is returned.

  *
*

A null input String returns null. * A null open/close returns null (no match). * An empty ("") open and close returns an empty string.

  *
*
   * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
   * StringUtils.substringBetween(null, *, *)          = null
   * StringUtils.substringBetween(*, null, *)          = null
   * StringUtils.substringBetween(*, *, null)          = null
   * StringUtils.substringBetween("", "", "")          = ""
   * StringUtils.substringBetween("", "", "]")         = null
   * StringUtils.substringBetween("", "[", "]")        = null
   * StringUtils.substringBetween("yabcz", "", "")     = ""
   * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
   * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
   * 
  *
  * @param str  the String containing the substring, may be null
  * @param open  the String before the substring, may be null
  * @param close  the String after the substring, may be null
  * @return the substring, null if no match
  * @since 2.0
  */
 public static String substringBetween(String str, String open, String close) {
     if (str == null || open == null || close == null) {
         return null;
     }
     int start = str.indexOf(open);
     if (start != -1) {
         int end = str.indexOf(close, start + open.length());
         if (end != -1) {
             return str.substring(start + open.length(), end);
         }
     }
     return null;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Gets the String that is nested in between two Strings. Only the first match is returned.

   <source lang="java">
 

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


/**

*

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 {

 // Substring between
 //-----------------------------------------------------------------------
 /**
*

Gets the String that is nested in between two instances of the * same String.

  *
*

A null input String returns null. * A null tag returns null.

  *
*
   * StringUtils.substringBetween(null, *)            = null
   * StringUtils.substringBetween("", "")             = ""
   * StringUtils.substringBetween("", "tag")          = null
   * StringUtils.substringBetween("tagabctag", null)  = null
   * StringUtils.substringBetween("tagabctag", "")    = ""
   * StringUtils.substringBetween("tagabctag", "tag") = "abc"
   * 
  *
  * @param str  the String containing the substring, may be null
  * @param tag  the String before and after the substring, may be null
  * @return the substring, null if no match
  * @since 2.0
  */
 public static String substringBetween(String str, String tag) {
     return substringBetween(str, tag, tag);
 }
 /**
*

Gets the String that is nested in between two Strings. * Only the first match is returned.

  *
*

A null input String returns null. * A null open/close returns null (no match). * An empty ("") open and close returns an empty string.

  *
*
   * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
   * StringUtils.substringBetween(null, *, *)          = null
   * StringUtils.substringBetween(*, null, *)          = null
   * StringUtils.substringBetween(*, *, null)          = null
   * StringUtils.substringBetween("", "", "")          = ""
   * StringUtils.substringBetween("", "", "]")         = null
   * StringUtils.substringBetween("", "[", "]")        = null
   * StringUtils.substringBetween("yabcz", "", "")     = ""
   * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
   * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
   * 
  *
  * @param str  the String containing the substring, may be null
  * @param open  the String before the substring, may be null
  * @param close  the String after the substring, may be null
  * @return the substring, null if no match
  * @since 2.0
  */
 public static String substringBetween(String str, String open, String close) {
     if (str == null || open == null || close == null) {
         return null;
     }
     int start = str.indexOf(open);
     if (start != -1) {
         int end = str.indexOf(close, start + open.length());
         if (end != -1) {
             return str.substring(start + open.length(), end);
         }
     }
     return null;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Gets the substring after the first occurrence of a separator. The separator is not returned.

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

 /**
*

Gets the substring after the first occurrence of a separator. * The separator is not returned.

  *
*

A null string input will return null. * An empty ("") string input will return the empty string. * A null separator will return the empty string if the * input string is not null.

  *
*
   * StringUtils.substringAfter(null, *)      = null
   * StringUtils.substringAfter("", *)        = ""
   * StringUtils.substringAfter(*, null)      = ""
   * StringUtils.substringAfter("abc", "a")   = "bc"
   * StringUtils.substringAfter("abcba", "b") = "cba"
   * StringUtils.substringAfter("abc", "c")   = ""
   * StringUtils.substringAfter("abc", "d")   = ""
   * StringUtils.substringAfter("abc", "")    = "abc"
   * 
  *
  * @param str  the String to get a substring from, may be null
  * @param separator  the String to search for, may be null
  * @return the substring after the first occurrence of the separator,
  *  null if null String input
  * @since 2.0
  */
 public static String substringAfter(String str, String separator) {
     if (isEmpty(str)) {
         return str;
     }
     if (separator == null) {
         return "";
     }
     int pos = str.indexOf(separator);
     if (pos == -1) {
         return "";
     }
     return str.substring(pos + separator.length());
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Gets the substring after the last occurrence of a separator. The separator is not returned.

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

 /**
*

Gets the substring after the last occurrence of a separator. * The separator is not returned.

  *
*

A null string input will return null. * An empty ("") string input will return the empty string. * An empty or null separator will return the empty string if * the input string is not null.

  *
*
   * StringUtils.substringAfterLast(null, *)      = null
   * StringUtils.substringAfterLast("", *)        = ""
   * StringUtils.substringAfterLast(*, "")        = ""
   * StringUtils.substringAfterLast(*, null)      = ""
   * StringUtils.substringAfterLast("abc", "a")   = "bc"
   * StringUtils.substringAfterLast("abcba", "b") = "a"
   * StringUtils.substringAfterLast("abc", "c")   = ""
   * StringUtils.substringAfterLast("a", "a")     = ""
   * StringUtils.substringAfterLast("a", "z")     = ""
   * 
  *
  * @param str  the String to get a substring from, may be null
  * @param separator  the String to search for, may be null
  * @return the substring after the last occurrence of the separator,
  *  null if null String input
  * @since 2.0
  */
 public static String substringAfterLast(String str, String separator) {
     if (isEmpty(str)) {
         return str;
     }
     if (isEmpty(separator)) {
         return "";
     }
     int pos = str.lastIndexOf(separator);
     if (pos == -1 || pos == (str.length() - separator.length())) {
         return "";
     }
     return str.substring(pos + separator.length());
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Gets the substring before the first occurrence of a separator. The separator is not returned.

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

 //-----------------------------------------------------------------------
 /**
*

Gets the substring before the first occurrence of a separator. * The separator is not returned.

  *
*

A null string input will return null. * An empty ("") string input will return the empty string. * A null separator will return the input string.

  *
*
   * StringUtils.substringBefore(null, *)      = null
   * StringUtils.substringBefore("", *)        = ""
   * StringUtils.substringBefore("abc", "a")   = ""
   * StringUtils.substringBefore("abcba", "b") = "a"
   * StringUtils.substringBefore("abc", "c")   = "ab"
   * StringUtils.substringBefore("abc", "d")   = "abc"
   * StringUtils.substringBefore("abc", "")    = ""
   * StringUtils.substringBefore("abc", null)  = "abc"
   * 
  *
  * @param str  the String to get a substring from, may be null
  * @param separator  the String to search for, may be null
  * @return the substring before the first occurrence of the separator,
  *  null if null String input
  * @since 2.0
  */
 public static String substringBefore(String str, String separator) {
     if (isEmpty(str) || separator == null) {
         return str;
     }
     if (separator.length() == 0) {
         return "";
     }
     int pos = str.indexOf(separator);
     if (pos == -1) {
         return str;
     }
     return str.substring(0, pos);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Gets the substring before the last occurrence of a separator. The separator is not returned.

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

 /**
*

Gets the substring before the last occurrence of a separator. * The separator is not returned.

  *
*

A null string input will return null. * An empty ("") string input will return the empty string. * An empty or null separator will return the input string.

  *
*
   * StringUtils.substringBeforeLast(null, *)      = null
   * StringUtils.substringBeforeLast("", *)        = ""
   * StringUtils.substringBeforeLast("abcba", "b") = "abc"
   * StringUtils.substringBeforeLast("abc", "c")   = "ab"
   * StringUtils.substringBeforeLast("a", "a")     = ""
   * StringUtils.substringBeforeLast("a", "z")     = "a"
   * StringUtils.substringBeforeLast("a", null)    = "a"
   * StringUtils.substringBeforeLast("a", "")      = "a"
   * 
  *
  * @param str  the String to get a substring from, may be null
  * @param separator  the String to search for, may be null
  * @return the substring before the last occurrence of the separator,
  *  null if null String input
  * @since 2.0
  */
 public static String substringBeforeLast(String str, String separator) {
     if (isEmpty(str) || isEmpty(separator)) {
         return str;
     }
     int pos = str.lastIndexOf(separator);
     if (pos == -1) {
         return str;
     }
     return str.substring(0, pos);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Getting a substring from a String

   <source lang="java">
   

public class Main {

 public static void main(String[] args) {
   String str = "this is a test";
   String sub = str.substring(10, 13);
   System.out.println(sub);
   sub = str.substring(10);
   System.out.println(sub);
 }

} /* tes test

  • /



 </source>
   
  
 
  



Last occurrence of a substring

   <source lang="java">
   

public class Main {

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

}



 </source>
   
  
 
  



Overlays part of a String with another String.

   <source lang="java">
  

import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; /*

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

 /**
*

Overlays part of a String with another String.

  *
*

A null string input returns null. * A negative index is treated as zero. * An index greater than the string length is treated as the string length. * The start index is always the smaller of the two indices.

  *
*
   * StringUtils.overlay(null, *, *, *)            = null
   * StringUtils.overlay("", "abc", 0, 0)          = "abc"
   * StringUtils.overlay("abcdef", null, 2, 4)     = "abef"
   * StringUtils.overlay("abcdef", "", 2, 4)       = "abef"
   * StringUtils.overlay("abcdef", "", 4, 2)       = "abef"
   * StringUtils.overlay("abcdef", "zzzz", 2, 4)   = "abzzzzef"
   * StringUtils.overlay("abcdef", "zzzz", 4, 2)   = "abzzzzef"
   * StringUtils.overlay("abcdef", "zzzz", -1, 4)  = "zzzzef"
   * StringUtils.overlay("abcdef", "zzzz", 2, 8)   = "abzzzz"
   * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
   * StringUtils.overlay("abcdef", "zzzz", 8, 10)  = "abcdefzzzz"
   * 
  *
  * @param str  the String to do overlaying in, may be null
  * @param overlay  the String to overlay, may be null
  * @param start  the position to start overlaying at
  * @param end  the position to stop overlaying before
  * @return overlayed String, null if null String input
  * @since 2.0
  */
 public static String overlay(String str, String overlay, int start, int end) {
     if (str == null) {
         return null;
     }
     if (overlay == null) {
         overlay = "";
     }
     int len = str.length();
     if (start < 0) {
         start = 0;
     }
     if (start > len) {
         start = len;
     }
     if (end < 0) {
         end = 0;
     }
     if (end > len) {
         end = len;
     }
     if (start > end) {
         int temp = start;
         start = end;
         end = temp;
     }
     return new StringBuffer(len + start - end + overlay.length() + 1)
         .append(str.substring(0, start))
         .append(overlay)
         .append(str.substring(end))
         .toString();
 }

}


 </source>
   
  
 
  



Remove a character at a specified position using String.substring

   <source lang="java">
   

public class Main {

 public static void main(String args[]) {
   String str = "this is a test";
   System.out.println(removeCharAt(str, 3));
 }
 public static String removeCharAt(String s, int pos) {
   return s.substring(0, pos) + s.substring(pos + 1);
 }

}



 </source>
   
  
 
  



Return a slice (substring) of the passed in value, optionally trimmed.

   <source lang="java">
 

/*

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 {

 /**
  * Return a slice (substring) of the passed in value, optionally trimmed.
  * WARNING - endOffset is inclusive for historical reasons, unlike
  * String.substring() which has an exclusive ending offset.
  * 
  * @param value
  *          Value to slice, must be non-null.
  * @param beginOffset
  *          Inclusive start character
  * @param endOffset
  *          Inclusive end character
  * @param trim
  *          To trim or not to trim
  * @return Sliceed value.
  */
 public static String slice(String value, int beginOffset, int endOffset, boolean trim) {
   String retval = value.substring(beginOffset, endOffset + 1);
   if (trim)
     retval = retval.trim();
   return retval;
 }

}


 </source>
   
  
 
  



SubString Demo

   <source lang="java">
   

/*

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

public class SubStringDemo {

 public static void main(String[] av) {
   String a = "Java is great.";
   System.out.println(a);
   String b = a.substring(5);  // b is the String "is great."
   System.out.println(b);
   String c = a.substring(5,7);// c is the String "is"
   System.out.println(c);
   String d = a.substring(5,a.length());// d is "is great."
   System.out.println(d);
 }

}



 </source>
   
  
 
  



Substrings First occurrence

   <source lang="java">
   

public class Main {

 public static void main(String[] argv) throws Exception {
   String string = "I am Java";
   int index = string.indexOf("dam"); // 1
 }

}



 </source>
   
  
 
  



uses substrings to replace all the vowels in a string entered by the user with asterisks:

   <source lang="java">
    

import java.util.Scanner; public class MarkVowels {

 static Scanner sc = new Scanner(System.in);
 public static void main(String[] args) {
   System.out.print("Enter a string: ");
   String s = sc.nextLine();
   String originalString = s;
   for (int i = 0; i < s.length(); i++) {
     char c = s.charAt(i);
     if ((c == "A") || (c == "a") || (c == "E") || (c == "e") || (c == "I") || (c == "i")
         || (c == "O") || (c == "o") || (c == "U") || (c == "u")) {
       String front = s.substring(0, i);
       String back = s.substring(i + 1);
       s = front + "*" + back;
     }
   }
   System.out.println(originalString);
   System.out.println(s);
 }

}



 </source>