Java Tutorial/Data Type/Substring
Содержание
- 1 Counts how many times the substring appears in the larger String.
- 2 Count the number of instances of substring within a string
- 3 Gets a substring from the specified String avoiding exceptions.
- 4 Gets len characters from the middle of a String.
- 5 Gets the leftmost len characters of a String
- 6 Gets the rightmost len characters of a String.
- 7 Gets the String that is nested in between two instances of the same String.
- 8 Gets the String that is nested in between two Strings. Only the first match is returned.
- 9 Gets the substring after the first occurrence of a separator. The separator is not returned.
- 10 Gets the substring before the last occurrence of a separator. The separator is not returned.
- 11 Get the difference between two strings
- 12 Removes a substring only if it is at the begining of a source string, otherwise returns the source string.
- 13 Removes a substring only if it is at the end of a source string, otherwise returns the source string.
- 14 Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.
- 15 Substitute sub-strings in side of a string
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 returns0
. *
* 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>
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 {
/** * Gets a substring from the specified String avoiding exceptions. * * A negative start position can be used to start/end*n
* characters from the end of the String. * * The returned substring starts with the character in thestart
* position and ends before theend
position. All position counting is * zero-based -- i.e., to start at the beginning of the string use *start = 0
. Negative start and end positions can be used to * specify offsets relative to the end of the String. * * Ifstart
is not strictly to the left ofend
, "" * is returned. *
* StringUtils.substring(null, *, *) = null * StringUtils.substring("", * , *) = ""; * StringUtils.substring("abc", 0, 2) = "ab" * StringUtils.substring("abc", 2, 0) = "" * StringUtils.substring("abc", 2, 4) = "c" * StringUtils.substring("abc", 4, 6) = "" * StringUtils.substring("abc", 2, 2) = "" * StringUtils.substring("abc", -2, -1) = "b" * StringUtils.substring("abc", -4, 2) = "ab" *
*
* @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
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end positon,
* null
if null String input
*/
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return "";
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
}</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. * * Iflen
characters are not available, the remainder * of the String will be returned without an exception. If the * String isnull
,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 leftmost len characters 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 the leftmost*len
characters of a String. * * Iflen
characters are not available, or the * String isnull
, the String will be returned without * an exception. An exception is thrown if len is negative. *
* StringUtils.left(null, *) = null * StringUtils.left(*, -ve) = "" * StringUtils.left("", *) = "" * StringUtils.left("abc", 0) = "" * StringUtils.left("abc", 2) = "ab" * StringUtils.left("abc", 4) = "abc" *
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the leftmost characters, null
if null String input
*/
public static String left(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return "";
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
}</source>
Gets the rightmost len characters 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 the rightmost*len
characters of a String. * * Iflen
characters are not available, or the String * isnull
, the String will be returned without an * an exception. An exception is thrown if len is negative. *
* StringUtils.right(null, *) = null * StringUtils.right(*, -ve) = "" * StringUtils.right("", *) = "" * StringUtils.right("abc", 0) = "" * StringUtils.right("abc", 2) = "bc" * StringUtils.right("abc", 4) = "abc" *
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String, must be zero or positive
* @return the rightmost characters, null
if null String input
*/
public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return "";
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - 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 returnsnull
. * Anull
tag returnsnull
. *
* 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. * * Anull
input String returnsnull
. * Anull
open/close returnsnull
(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 returnsnull
. * Anull
tag returnsnull
. *
* 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. * * Anull
input String returnsnull
. * Anull
open/close returnsnull
(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 returnnull
. * An empty ("") string input will return the empty string. * Anull
separator will return the empty string if the * input string is notnull
. *
* 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 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 returnnull
. * An empty ("") string input will return the empty string. * An empty ornull
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>
Get the difference 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 Utils {
public static String diff(String str1, String str2) { int index = str1.lastIndexOf(str2); if (index > -1) { return str1.substring(str2.length()); } return str1; }
}</source>
Removes a substring only if it is at the begining of a source string, otherwise returns the source 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 {
// Remove //----------------------------------------------------------------------- /** * Removes a substring only if it is at the begining of a source string, * otherwise returns the source string. * * A*null
source string will returnnull
. * An empty ("") source string will return the empty string. * Anull
search string will return the source string. *
* StringUtils.removeStart(null, *) = null * StringUtils.removeStart("", *) = "" * StringUtils.removeStart(*, null) = * * StringUtils.removeStart("www.domain.ru", "www.") = "domain.ru" * StringUtils.removeStart("domain.ru", "www.") = "domain.ru" * StringUtils.removeStart("www.domain.ru", "domain") = "www.domain.ru" * StringUtils.removeStart("abc", "") = "abc" *
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* null
if null String input
* @since 2.1
*/
public static String removeStart(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)){
return str.substring(remove.length());
}
return str;
}
// 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>
Removes a substring only if it is at the end of a source string, otherwise returns the source 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 {
/** * Removes a substring only if it is at the end of a source string, * otherwise returns the source string. * * A*null
source string will returnnull
. * An empty ("") source string will return the empty string. * Anull
search string will return the source string. *
* StringUtils.removeEnd(null, *) = null * StringUtils.removeEnd("", *) = "" * StringUtils.removeEnd(*, null) = * * StringUtils.removeEnd("www.domain.ru", ".ru.") = "www.domain.ru" * StringUtils.removeEnd("www.domain.ru", ".ru") = "www.domain" * StringUtils.removeEnd("www.domain.ru", "domain") = "www.domain.ru" * StringUtils.removeEnd("abc", "") = "abc" *
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* null
if null String input
* @since 2.1
*/
public static String removeEnd(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
// 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>
Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.
<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 {
/** * Searches a String for substrings delimited by a start and end tag, * returning all matching substrings in an array. * * A*null
input String returnsnull
. * Anull
open/close returnsnull
(no match). * An empty ("") open/close returnsnull
(no match). *
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"] * StringUtils.substringsBetween(null, *, *) = null * StringUtils.substringsBetween(*, null, *) = null * StringUtils.substringsBetween(*, *, null) = null * StringUtils.substringsBetween("", "[", "]") = [] *
*
* @param str the String containing the substrings, null returns null, empty returns empty
* @param open the String identifying the start of the substring, empty returns null
* @param close the String identifying the end of the substring, empty returns null
* @return a String Array of substrings, or null
if no match
* @since 2.3
*/
public static String[] substringsBetween(String str, String open, String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
int strLen = str.length();
if (strLen == 0) {
return new String[0];
}
int closeLen = close.length();
int openLen = open.length();
List list = new ArrayList();
int pos = 0;
while (pos < (strLen - closeLen)) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return (String[]) list.toArray(new String [list.size()]);
}
// Empty checks
//-----------------------------------------------------------------------
/**
* 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>
Substitute sub-strings in side of a string
<source lang="java">
import java.util.Map;
/*
* JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
public class Main{
/** An empty string constant */
public static final String EMPTY = "";
/////////////////////////////////////////////////////////////////////////
// Substitution Methods //
/////////////////////////////////////////////////////////////////////////
/**
* Substitute sub-strings in side of a string.
*
* @param buff Stirng buffer to use for substitution (buffer is not reset)
* @param from String to substitute from
* @param to String to substitute to
* @param string String to look for from in
* @return Substituted string
*/
public static String subst(final StringBuffer buff, final String from,
final String to, final String string)
{
int begin = 0, end = 0;
while ((end = string.indexOf(from, end)) != -1)
{
// append the first part of the string
buff.append(string.substring(begin, end));
// append the replaced string
buff.append(to);
// update positions
begin = end + from.length();
end = begin;
}
// append the rest of the string
buff.append(string.substring(begin, string.length()));
return buff.toString();
}
/**
* Substitute sub-strings in side of a string.
*
* @param from String to substitute from
* @param to String to substitute to
* @param string String to look for from in
* @return Substituted string
*/
public static String subst(final String from, final String to,
final String string)
{
return subst(new StringBuffer(), from, to, string);
}
/**
* Substitute sub-strings in side of a string.
*
* @param buff String buffer to use for substitution (buffer is not reset)
* @param string String to subst mappings in
* @param map Map of from->to strings
* @param beginToken Beginning token
* @param endToken Ending token
* @return Substituted string
*/
public static String subst(final StringBuffer buff, final String string,
final Map map, final String beginToken,
final String endToken)
{
int begin = 0, rangeEnd = 0;
Range range;
while ((range = rangeOf(beginToken, endToken, string, rangeEnd)) != null)
{
// append the first part of the string
buff.append(string.substring(begin, range.begin));
// Get the string to replace from the map
String key = string.substring(range.begin + beginToken.length(),
range.end);
Object value = map.get(key);
// if mapping does not exist then use empty;
if (value == null) value = EMPTY;
// append the replaced string
buff.append(value);
// update positions
begin = range.end + endToken.length();
rangeEnd = begin;
}
// append the rest of the string
buff.append(string.substring(begin, string.length()));
return buff.toString();
}
/**
* Substitute sub-strings in side of a string.
*
* @param string String to subst mappings in
* @param map Map of from->to strings
* @param beginToken Beginning token
* @param endToken Ending token
* @return Substituted string
*/
public static String subst(final String string, final Map map,
final String beginToken, final String endToken)
{
return subst(new StringBuffer(), string, map, beginToken, endToken);
}
/**
* Substitute index identifiers with the replacement value from the
* given array for the corresponding index.
*
* @param buff The string buffer used for the substitution
* (buffer is not reset).
* @param string String substitution format.
* @param replace Array of strings whose values will be used as
* replacements in the given string when a token with
* their index is found.
* @param token The character token to specify the start of an index
* reference.
* @return Substituted string.
*/
public static String subst(final StringBuffer buff, final String string,
final String replace[], final char token)
{
int i = string.length();
for (int j = 0; j >= 0 && j < i; j++)
{
char c = string.charAt(j);
// if the char is the token, then get the index
if (c == token)
{
// if we aren"t at the end of the string, get the index
if (j != i)
{
int k = Character.digit(string.charAt(j + 1), 10);
if (k == -1)
{
buff.append(string.charAt(j + 1));
}
else if (k < replace.length)
{
buff.append(replace[k]);
}
j++;
}
}
else
{
buff.append(c);
}
}
return buff.toString();
}
/**
* Substitute index identifiers with the replacement value from the
* given array for the corresponding index.
*
* @param string String substitution format.
* @param replace Array of strings whose values will be used as
* replacements in the given string when a token with
* their index is found.
* @param token The character token to specify the start of an index
* reference.
* @return Substituted string.
*/
public static String subst(final String string, final String replace[],
final char token)
{
return subst(new StringBuffer(), string, replace, token);
}
/**
* Substitute index identifiers (with %
for the index token)
* with the replacement value from the given array for the corresponding
* index.
*
* @param string String substitution format.
* @param replace Array of strings whose values will be used as
* replacements in the given string when a token with
* their index is found.
* @return Substituted string.
*/
public static String subst(final String string, final String replace[])
{
return subst(new StringBuffer(), string, replace, "%");
}
/////////////////////////////////////////////////////////////////////////
// Range Methods //
/////////////////////////////////////////////////////////////////////////
/**
* Represents a range between two integers.
*/
public static class Range
{
/** The beginning of the range. */
public int begin;
/** The end of the range. */
public int end;
/**
* Construct a new range.
*
* @param begin The beginning of the range.
* @param end The end of the range.
*/
public Range(int begin, int end)
{
this.begin = begin;
this.end = end;
}
/**
* Default constructor.
*/
public Range()
{
}
}
/**
* Return the range from a begining token to an ending token.
*
* @param beginToken String to indicate begining of range.
* @param endToken String to indicate ending of range.
* @param string String to look for range in.
* @param fromIndex Beginning index.
* @return (begin index, end index) or null.
*/
public static Range rangeOf(final String beginToken, final String endToken,
final String string, final int fromIndex)
{
int begin = string.indexOf(beginToken, fromIndex);
if (begin != -1)
{
int end = string.indexOf(endToken, begin + 1);
if (end != -1)
{
return new Range(begin, end);
}
}
return null;
}
/**
* Return the range from a begining token to an ending token.
*
* @param beginToken String to indicate begining of range.
* @param endToken String to indicate ending of range.
* @param string String to look for range in.
* @return (begin index, end index) or null.
*/
public static Range rangeOf(final String beginToken, final String endToken,
final String string)
{
return rangeOf(beginToken, endToken, string, 0);
}
}</source>