org.eclipse.leshan.util.StringUtils Maven / Gradle / Ivy
Show all versions of leshan-all Show documentation
/*
* 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.
*/
package org.eclipse.leshan.util;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
*
* Operations on {@link java.lang.String} that are null
safe.
*
*
*
* - IsEmpty/IsBlank - checks if a String contains text
* - Trim/Strip - removes leading and trailing whitespace
* - Equals - compares two strings null-safe
* - startsWith - check if a String starts with a prefix null-safe
* - endsWith - check if a String ends with a suffix null-safe
* - IndexOf/LastIndexOf/Contains - null-safe index-of checks
*
- IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
* - ContainsOnly/ContainsNone/ContainsAny - does String contains only/none/any of these characters
* - Substring/Left/Right/Mid - null-safe substring extractions
* - SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
* - Split/Join - splits a String into an array of substrings and vice versa
* - Remove/Delete - removes part of a String
* - Replace/Overlay - Searches a String and replaces one String with another
* - Chomp/Chop - removes the last part of a String
* - LeftPad/RightPad/Center/Repeat - pads a String
* - UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
* - CountMatches - counts the number of occurrences of one String in another
* - IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
* - DefaultString - protects against a null input String
* - Reverse/ReverseDelimited - reverses a String
* - Abbreviate - abbreviates a string using ellipsis
* - Difference - compares Strings and reports on their differences
* - LevensteinDistance - the number of changes needed to change one String into another
*
*
*
* The StringUtils
class defines certain words related to String handling.
*
*
*
* - null -
null
* - empty - a zero-length string (
""
)
* - space - the space character (
' '
, char 32)
* - whitespace - the characters defined by {@link Character#isWhitespace(char)}
* - trim - the characters <= 32 as in {@link String#trim()}
*
*
*
* StringUtils
handles null
input Strings quietly. That is to say that a null
* input will return null
. Where a boolean
or int
is being returned details vary
* by method.
*
*
*
* A side effect of the null
handling is that a NullPointerException
should be considered a
* bug in StringUtils
(except for deprecated methods).
*
*
*
* Methods in this class give sample code to explain their operation. The symbol *
is used to indicate any
* input including null
.
*
*
*
* #ThreadSafe#
*
*
* @see java.lang.String
* @author Apache Software Foundation
* @author Apache Jakarta Turbine
* @author Jon S. Stevens
* @author Daniel L. Rall
* @author Greg Coladonato
* @author Ed Korthof
* @author Rand McNeely
* @author Fredrik Westermarck
* @author Holger Krauth
* @author Alexander Day Chaffee
* @author Henning P. Schmiedehausen
* @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 1058365 2011-01-13 00:04:49Z niallp $
*/
// @Immutable
public class StringUtils {
// Equals
// -----------------------------------------------------------------------
/**
*
* Compares two Strings, returning true
if they are equal.
*
*
*
* null
s are handled without exceptions. Two null
references are considered to be equal.
* The comparison is case sensitive.
*
*
*
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
*
*
* @see java.lang.String#equals(Object)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return true
if the Strings are equal, case sensitive, or both null
*/
public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2);
}
/**
*
* Compares two Strings, returning true
if they are equal ignoring the case.
*
*
*
* null
s are handled without exceptions. Two null
references are considered equal.
* Comparison is case insensitive.
*
*
*
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
*
*
* @see java.lang.String#equalsIgnoreCase(String)
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return true
if the Strings are equal, case insensitive, or both null
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
}
// 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;
}
// Trim
// -----------------------------------------------------------------------
/**
*
* Removes control characters (char <= 32) from both ends of this String, handling null
by returning
* null
.
*
*
*
* The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32. To strip
* whitespace use {@link #strip(String)}.
*
*
*
* To trim your choice of characters, use the {@link #strip(String, String)} methods.
*
*
*
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
*
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, null
if null String input
*/
public static String trim(String str) {
return str == null ? null : str.trim();
}
// Remove
// -----------------------------------------------------------------------
/**
*
* Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.
*
*
*
* A null
source string will return null
. An empty ("") source string will return the
* empty string. A null
search string will return the source string.
*
*
*
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* 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;
}
/**
*
* Removes a substring only if it is at the end of a source string, otherwise returns the source string.
*
*
*
* A null
source string will return null
. An empty ("") source string will return the
* empty string. A null
search string will return the source string.
*
*
*
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* 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;
}
/**
* Constructs a new String
by decoding the specified array of bytes using the given charset.
*
* @param bytes The bytes to be decoded into characters
* @param charset The {@link Charset} to encode the String
* @return A new String
decoded from the specified array of bytes using the given charset, or
* null
if the input byte array was null
.
* @throws NullPointerException Thrown if {@link StandardCharsets#UTF_8} is not initialized, which should never happen since
* it is required by the Java platform specification.
*/
private static String newString(final byte[] bytes, final Charset charset) {
return bytes == null ? null : new String(bytes, charset);
}
/**
* Constructs a new String
by decoding the specified array of bytes using the UTF-8 charset.
*
* @param bytes The bytes to be decoded into characters
* @return A new String
decoded from the specified array of bytes using the UTF-8 charset, or
* null
if the input byte array was null
.
* @throws NullPointerException Thrown if {@link StandardCharsets#UTF_8} is not initialized, which should never happen since
* it is required by the Java platform specification.
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
*/
public static String newStringUtf8(final byte[] bytes) {
return newString(bytes, StandardCharsets.UTF_8);
}
/**
* Calls {@link String#getBytes(Charset)}
*
* @param string The string to encode (if null, return null).
* @param charset The {@link Charset} to encode the String
* @return the encoded bytes
*/
private static byte[] getBytes(final String string, final Charset charset) {
if (string == null) {
return null;
}
return string.getBytes(charset);
}
/**
* Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
* array.
*
* @param string the String to encode, may be null
* @return encoded bytes, or null
if the input string was null
* @throws NullPointerException Thrown if {@link StandardCharsets#UTF_8} is not initialized, which should never happen since
* it is required by the Java platform specification.
* @since As of 1.7, throws {@link NullPointerException} instead of UnsupportedEncodingException
* @see Standard charsets
* @see #getBytesUnchecked(String, String)
*/
public static byte[] getBytesUtf8(final String string) {
return getBytes(string, StandardCharsets.UTF_8);
}
/**
* Checks if the String contains only unicode digits.
* A decimal point is not a unicode digit and returns false.
*
* null
will return false
.
* An empty String (length()=0) will return true
.
*
*
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
*
*
* @param str the String to check, may be null
* @return true
if only contains digits, and is non-null
*/
public static boolean isNumeric(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
}