Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
jerry - Common Java Functionality Copyright (c) 2012-2015, Sandeep Gupta http://sangupta.com/projects/jerry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
  
 package com.sangupta.jerry.util;
 
 import java.util.List;
 
Utility functions around java.lang.String objects.

Author(s):
sangupta
 
 public class StringUtils {

Logger instance
 
 	public static final Logger LOGGER = LoggerFactory.getLogger(StringUtils.class);

UTF-8 charset object
 
 	public static final Charset CHARSET_UTF8 = Charset.forName("UTF8");

An empty string object containing nothing.
 
 	public static final String EMPTY_STRING = "";

A blank string containing one blank white-space character.
 
 	public static final String BLANK_STRING = " ";

A String[] array that is empty and contains no elements
 
 	public static final String[] EMPTY_STRING_LIST = new String[] { };

Defines the platform dependent line encoding
 
 	public static final String SYSTEM_NEW_LINE = System.getProperty("line.separator");

Function to give a HEX representation of the byte array in small-case.

Parameters:
bytes the source byte array
Returns:
the HEX coded string representing the byte array
 
 	public static String asHex(byte bytes[]) {
 		StringBuilder sb = new StringBuilder();
 		for (int i = 0; i < bytes.length; ++i) {
 			sb.append(Integer.toHexString((bytes[i] & 0xFF) | 0x100).substring(1, 3));
 		}
 		return sb.toString();
 	}

Function to return a HEX representation of the given byte in small-case.

Parameters:
b the byte value
Returns:
the hex representation
 
 	public static String asHex(byte b) {
 		return Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3);
 	}

Return the java.lang.String representation of the byte array. A null byte array is converted back to null, an empty array to an empty string or the bytes to the actual string based on platform encoding.

Parameters:
bytes the byte array
Returns:
its string representation
	public static String asString(byte[] bytes) {
		if(bytes == null) {
			return null;
		}
		if(bytes.length == 0) {
			return ;
		}
		return new String(bytes);
	}

Return the java.lang.String representation of the byte array. A null byte array is converted back to null, an empty array to an empty string or the bytes to the actual string in UTF-8 encoding.

Parameters:
bytes the byte array
Returns:
its string representation
	public static String asStringUTF8(byte[] bytes) {
		if(bytes == null) {
			return null;
		}
		if(bytes.length == 0) {
			return ;
		}
		return new String(bytes);
	}

Return the actual array that this hex string represents.

Parameters:
hex the hex string
Returns:
the actual byte array for the hex string
	public static byte[] fromHex(String hex) {
		if(AssertUtils.isEmpty(hex)) {
			return null;
		}
		int len = hex.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < leni += 2) {
	        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i+1), 16));
	    }
	    
	    return data;
	}

Return true if the string is equal to "true" or "yes" otherwise return false.

Parameters:
boolString string whose content is checked for true or false
Returns:
boolean flag indicating whether the input was true or false
	public static boolean getBoolean(String boolString) {
	    return getBoolean(boolStringfalse); 
 	}

Parse the string and return the boolean value for the same. Text such as yes and true is treated as java.lang.Boolean.TRUE . If the string parsing fails, the default value is returned.

Parameters:
boolString the string to be parsed
defaultValue the value to be returned, if the string does not match
Returns:
the boolean value as read by parsing the string
	public static boolean getBoolean(String boolStringboolean defaultValue) {
		if (AssertUtils.isNotEmpty(boolString)) {
	        boolString = boolString.toLowerCase();
	        if ("yes".equals(boolString) || "true".equals(boolString)) {
	            return true;
	        }
	        
	        return false;
	    }
	    return defaultValue
 	}

Parse and return the short value of the given string. If the string cannot be parsed, returns the default value provided

Parameters:
string the string to be parsed
defaultValue the value to be returned if parsing string fails
Returns:
the 32-bit value of the string
	public static short getShortValue(String stringshort defaultValue) {
		try {
			if(AssertUtils.isNotEmpty(string)) {
				return Short.parseShort(string);
			}
catch(NumberFormatException e) {
			.debug("error getting integer from string: " + stringe);
		}
		return defaultValue;
	}

Parse and return the int value of the given string. If the string cannot be parsed, returns the default value provided

Parameters:
string the string to be parsed
defaultValue the value to be returned if parsing string fails
Returns:
the 32-bit value of the string
	public static int getIntValue(String stringint defaultValue) {
		try {
			if(AssertUtils.isNotEmpty(string)) {
				return Integer.parseInt(string);
			}
catch(NumberFormatException e) {
			.debug("error getting integer from string: " + stringe);
		}
		return defaultValue;
	}

Parse and return the long value of the given string. If the string cannot be parsed, returns the default value provided

Parameters:
string the string to be parsed
defaultValue the value to be returned if parsing string fails
Returns:
the 64-bit value of the string
	public static long getLongValue(String stringlong defaultValue) {
		try {
			if(AssertUtils.isNotEmpty(string)) {
				return Long.parseLong(string);
			}
catch(NumberFormatException e) {
			.debug("error getting long from string: " + stringe);
		}
		return defaultValue;
	}

Parse and return the float value of the given string. If the string cannot be parsed, returns the default value provided

Parameters:
string the string to be parsed
defaultValue the value to be returned if parsing string fails
Returns:
the float value of the string
	public static float getFloatValue(String stringfloat defaultValue) {
		try {
			if(AssertUtils.isNotEmpty(string)) {
				return Float.parseFloat(string);
			}
catch(NumberFormatException e) {
			.debug("error getting long from string: " + stringe);
		}
		return defaultValue;
	}

Parse and return the double value of the given string. If the string cannot be parsed, returns the default value provided

Parameters:
string the string to be parsed
defaultValue the value to be returned if parsing string fails
Returns:
the double value of the string
	public static double getDoubleValue(String stringdouble defaultValue) {
		try {
			if(AssertUtils.isNotEmpty(string)) {
				return Double.parseDouble(string);
			}
catch(NumberFormatException e) {
			.debug("error getting long from string: " + stringe);
		}
		return defaultValue;
	}

Generate a given appender delimited string of all items in the list. If the list has no elements, an empty string is returned back.

Parameters:
list the list containing objects to be joined
appender the appender to be used
Returns:
the string representation of list using appender as the delimiter
	public static <T> String listToString(List<T> listString appender) {
		if(AssertUtils.isEmpty(list)) {
			return ;
		}
		final boolean hasAppender = AssertUtils.isNotEmpty(appender);
		StringBuilder builder = new StringBuilder();
		for(int index = 0; index < list.size(); index++) {
			if(hasAppender && index > 0) {
				builder.append(appender);
			}
			builder.append(list.get(index));
		}
		return builder.toString();
	}

Check if a value is contained in the list.

Parameters:
list the list of values
value the value that needs to be checked for presence in list
Returns:
true if the value exists in list, false otherwise.
	public static boolean contains(String[] listString value) {
		if(list == null) {
			return false;
		}
		if(list.length == 0) {
			return false;
		}
		for(String item : list) {
			if(item.equals(value)) {
				return true;
			}
		}
		return false;
	}

Return a subset of string from the location where the given 'from' word exists.

Parameters:
string the string from which substring needs to be extracted
from the string to be looked
searchIndex the index from which the string needs to be searched
Returns:
the substring after the word is found inside the main string
	public static String substringAfter(String stringString fromint searchIndex) {
		if(AssertUtils.isEmpty(string)) {
			return ;
		}
		if(AssertUtils.isEmpty(from)) {
			return string;
		}
		int index = string.indexOf(fromsearchIndex);
		if(index == -1) {
			return ;
		}
		return string.substring(index + from.length());
	}

Find the substring between the given prefix and suffix.

Parameters:
string the string which needs to be sub-string'ed
prefix the string before
suffix the string after
Returns:
the sub-string between the prefix and suffix
	public static String substringBetween(String stringString prefixString suffix) {
		return StringUtils.substringBetween(stringprefixsuffix, 0);
	}

Find the substring between the given prefix and suffix.

Parameters:
string the string which needs to be sub-string'ed
prefix the string before
suffix the string after
startSearch the index to start searching the prefix from
Returns:
the sub-string between the prefix and suffix
	public static String substringBetween(String stringString prefixString suffixint startSearch) {
		if(AssertUtils.isEmpty(string)) {
			return ;
		}
		int begin = 0, end = string.length();
		if(AssertUtils.isNotBlank(prefix)) {
			begin = string.indexOf(prefixstartSearch);
			if(begin != -1) {
				begin += prefix.length();
else {
				begin = 0;
			}
		}
		if(AssertUtils.isNotEmpty(suffix)) {
			end = string.indexOf(suffixbegin);
			if(end == -1) {
				end = string.length();
			}
		}
		return string.substring(beginend);
	}

Find the last index of searchString inside string, where searchString occurs before the suffix in the string.

Parameters:
string the string in which the search will be performed
searchString the string that needs to be searched
suffix the string that decides the end location of the search
Returns:
the index of searchString inside string, terminated at point where suffix occurs
	public static int lastIndexBefore(String stringString searchStringString suffix) {
		if(AssertUtils.isEmpty(string)) {
			return -1;
		}
		if(AssertUtils.isEmpty(searchString)) {
			return -1;
		}
		int index = string.indexOf(suffix);
		if(index != -1) {
			string = string.substring(0, index);
		}
		return string.lastIndexOf(searchString);
	}
	public static int lastIndexBefore(String stringString searchStringint maxSuffix) {
		if(AssertUtils.isEmpty(string)) {
			return -1;
		}
		if(AssertUtils.isEmpty(searchString)) {
			return -1;
		}
		if(maxSuffix == -1) {
			return string.lastIndexOf(searchString);
		}
		maxSuffix = maxSuffix - searchString.length() + 1;
		int start = -2;
		int index = -1;
		do {
			index = string.indexOf(searchStringstart + 1);
			if(index == -1) {
				break;
			}
			if(index >= maxSuffix) {
				index = start;
				break;
			}
			start = index;
while(true);
		if(start < 0) {
			return -1;
		}
		return start;
	}

Find the nth index of a string-part inside another string.

Parameters:
string the string in which the search will be performed
searchString the string that needs to be searched
n the occurrence number that we are looking for
Returns:
the index of nth occurrence of searchString inside string
	public static int nthIndexOf(String stringString searchStringint n) {
		if(n <= 0) {
			throw new IllegalArgumentException("n cannot be less than, or equal to zero");
		}
		if(n == 1) {
			return string.indexOf(searchString);
		}
		int count = 0;
		int index = -1;
		do {
			index = string.indexOf(searchStringindex + 1);
			if(index == -1) {
				return -1;
			}
			count++;
			if(count == n) {
				return index;
			}
while(true);
	}

Check if the given string starts with the given prefix, ignoring case.

Parameters:
text the string to search in
prefix the prefix to search for
Returns:
true if the string starts with prefix, false otherwise
	public static boolean startsWithIgnoreCase(String textString prefix) {
		if(AssertUtils.isEmpty(text)) {
			return false;
		}
		if(AssertUtils.isEmpty(prefix)) {
			return false;
		}
		if(text == prefix) {
			return true// same string
		}
		if(prefix.length() > text.length()) {
			return false;
		}
		if(text.substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
			return true;
		}
		return false;
	}

Check if the given string ends with the given suffix, ignoring case.

Parameters:
text the string to search in
suffix the suffix to search for
Returns:
true if the string ends with suffix, false otherwise
	public static boolean endsWithIgnoreCase(String textString suffix) {
		if(AssertUtils.isEmpty(text)) {
			return false;
		}
		if(AssertUtils.isEmpty(suffix)) {
			return false;
		}
		if(text == suffix) {
			return true// same string
		}
		int start = text.length() - suffix.length();
		if(start < 0) {
			return false;
		}
		if(text.substring(start).equalsIgnoreCase(suffix)) {
			return true;
		}
		return false;
	}

Merge the items into a single string separated by the given delimiter

Parameters:
items Items to be merged into a string
delimiter the character delimiter to be used
Returns:
the merged string
	public static String merge(String[] itemschar delimiter) {
		if(AssertUtils.isEmpty(items)) {
		}
		StringBuilder builder = new StringBuilder(1024);
		for(int index = 0; index < items.lengthindex++) {
			if(index > 0) {
				builder.append(delimiter);
			}
			builder.append(items[index]);
		}
		return builder.toString();
	}

Merge the items into a single string separated by the given delimiter

Parameters:
items Items to be merged into a string
delimiter the string delimiter to be used
Returns:
the merged string
	public static String merge(String[] itemsString delimiter) {
		if(AssertUtils.isEmpty(items)) {
		}
		boolean addDelimiter = AssertUtils.isNotEmpty(delimiter);
		StringBuilder builder = new StringBuilder(1024);
		for(int index = 0; index < items.lengthindex++) {
			if(addDelimiter) {
				if(index > 0) {
					builder.append(delimiter);
				}
			}
			builder.append(items[index]);
		}
		return builder.toString();
	}

Return a string containing the same character the given number of times.

Parameters:
ch
times
Returns:
	public static String repeat(char chint times) {
		if(times <= 0) {
			throw new IllegalArgumentException("Length cannot be less than or equal to zero");
		}
		if(times == 1) {
			return String.valueOf(ch);
		}
		char[] array = new char[times];
		Arrays.fill(arraych);
		return new String(array);
	}

Convert the property name to JSON valid property name. Convert all illegal characters to underscore.

Parameters:
name
Returns:
	public static String convertToJsonPropertyName(String name) {
		char[] chars = name.toCharArray();
		for(int index = 0; index < chars.lengthindex++) {
			char c = chars[index];
			if(!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || (c == '_') || (c == '-'))) {
				chars[index] = '_';
			}
		}
		return new String(chars);
	}

Convert the property name to XML valid property name. Convert all illegal characters to hyphen.

Parameters:
name
Returns:
	public static String convertToXmlPropertyName(String name) {
		char[] chars = name.toCharArray();
		for(int index = 0; index < chars.lengthindex++) {
			char c = chars[index];
			if(!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || (c == '_') || (c == '-'))) {
				chars[index] = '-';
			}
		}
		return new String(chars);
	}
New to GrepCode? Check out our FAQ X