Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Creative commons Attribution-NonCommercial license. http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
  
  package base.text;
  
Utility functions related to string management.
 
 public class StringHelper {
 
 	private static final Pattern REPLACE_QUOTE = Pattern.compile("'");
 	private static final Pattern REPLACE_DOUBLE_QUOTE = Pattern.compile("\"");
 	private static final Pattern REPLACE_LESS_THAN = Pattern.compile("<");
 	private static final Pattern REPLACE_GREATER_THAN = Pattern.compile(">");
 	private static final Pattern REPLACE_AMP = Pattern.compile("&");
 	private static final Pattern REPLACE_FORWARD_SLASH = Pattern.compile("/");
 
 	private static SecureRandom random = new SecureRandom();

Escape characters that are considered to be special HTML characters.

Parameters:
input String with potential special HTML characters.
Returns:
String with all special HTML characters properly formatted.
 
 	public static String escapeHtml(String input) {
 		if(input == null) {
 			return null;
 		}
 
 		Matcher matcher = .matcher(input);
 		input = matcher.replaceAll("&amp;");
 
 		// Prefer &#39; instead of &apos;
 		// See: http://www.w3.org/TR/2002/REC-xhtml1-20020801/#C_16
 		matcher = .matcher(input);
 		input = matcher.replaceAll("&#39;");
 
 		matcher = .matcher(input);
 		input = matcher.replaceAll("&#x2F;");
 
 		matcher = .matcher(input);
 		input = matcher.replaceAll("&quot;");
 
 		matcher=.matcher(input);
 		input = matcher.replaceAll("&lt;");
 
 		matcher=.matcher(input);
 		input = matcher.replaceAll("&gt;");
 
 		return input;
 	}

Escape characters that are considered to be special XML characters.

Parameters:
input String with potential special XML characters.
Returns:
String with all special XML characters properly formatted.
 
 	public static String escapeXml(String input) {
 		if(input == null) {
 			return null;
 		}
 
 		Matcher matcher = .matcher(input);
 		input = matcher.replaceAll("&quot;");
 
 		matcher = .matcher(input);
 		input = matcher.replaceAll("&apos;");
 
 		matcher=.matcher(input);
 		input = matcher.replaceAll("&lt;");
 
 		matcher=.matcher(input);
 		input = matcher.replaceAll("&gt;");
 
 		matcher = .matcher(input);
 		input = matcher.replaceAll("&amp;");
 
 		return input;
 	}

Limit the length of a string to a certain number of characters. If the string is truncated, a "..." is appended to the resulting string.

Parameters:
string
length
Returns:
The input string, limited to 'length' number of characters. String will end in '...' if it was truncated.
	public static String maxLength(String stringint length) {
		if(string.length() <= length || length < 4) {
			return string;
		}
		string = string.substring(0, length-3).trim();
		return string+"...";
	}

Display a number in bytes, kilobytes or megabytes.

Parameters:
size
Returns:
File size in "pretty" format
	public static String fileSizeToString(long size) {
		if(size >= (1024*1024) && size < (1024*1024*1024)) {
			return (size/1024/1024)+"Mb";
		}
		if(size >= 1024 && size < (1024*1024)) {
			return (size/1024)+"Kb";
		}
		return size+" bytes";
	}

Escape characters that should not be included in a variable in a URL. It is different to using URLEncoder.encode() because it escapes only what is really needed to be escaped for modern browsers. Technically it is incorrect, but it makes for much nicer looking URL's when working with non English languages.

Parameters:
input
Returns:
The input string, with a limited set of special characters escaped.
	public static String urlEscape(String input) {
		input = input.replace("%""%25");
		input = input.replace("+""%2B");
		input = input.replace("=""%3D");
		input = input.replace("#""%23");
		input = input.replace("/""%2F");
		input = input.replace("@""%40");
		input = input.replace("&""%26");
		input = input.replace("\n""%0A");
		input = input.replace("\r""%0C");
		input = input.replace("\"""%22");
		input = input.replace("<""%3C");
		input = input.replace(">""%3E");
		input = input.replace("'""%27");
		input = input.replace(" ""%20");
		return input;
	}

This method is deprecated in favour of the now built-in java function URLDecoder.decode(input, "utf-8")

Deprecated:
Deprecated in favor of URLDecoder.decode(input, "utf-8")
Parameters:
input String to be unescaped
Returns:
Returns the results of invoking URLDecoder.decode(input, "utf-8").
	public static String urlUnescape(String input) {
		try {
			return URLDecoder.decode(input"utf-8");
			throw new RuntimeException(e);
		}
	}

Return a string of random alphanumeric characters. Characters 0, O, l and 1 are excluded, to ensure if the string is written down, there is no confusion over these characters.

Parameters:
len Length of the rendom string.
Returns:
A string of random characters.
	public static String randomString(int len) {
		long r = .nextLong();
		if(r < 0) {
			r = -r;
		}
		// random chance to reseed
		if(r%100000L == 1L) {
		}
		String str = "";
		int i = 0;
		while(i < len) {
			int n = .nextInt()&31;
			int c = 'a';
			if(.nextInt() > 0) {
				c = 'A';
			}
			if(n > 25) {
				c = '0'+n-25;
else {
				c = c+n;
			}
			if(c == '0' || c == 'O' || c == 'l' || c == '1') {
				continue;
			}
			str = str+(char)(c);
			i++;
		}
		return str;
	}

Return SHA hashed version of a string.

Parameters:
string String to hash.
Returns:
Base 64 encoded SHA hash representing this string.
Throws:
java.security.NoSuchAlgorithmException
java.io.UnsupportedEncodingException
		MessageDigest md = MessageDigest.getInstance("SHA");
		md.update(string.getBytes("UTF-8"));
		return Base64Encode.encode(md.digest());
	}

Return the contents of 'string' or an empty string if it is null.

Parameters:
string The string
Returns:
the string or empty string.
	public static final String nullToEmptyString(String string) {
		return string == null ? "":string;
	}

Return the 'string' or the 'defaultValue' if the string is null.

Parameters:
string the object
defaultValue the alternative value
Returns:
the string or the default value
	public static final String nullToEmptyString(String stringString defaultValue) {
		return string == null ? defaultValue:string;
	}
	public static String join(String[] stringsString string) {
		StringBuffer buffer = new StringBuffer();
		for(String item : strings) {
			if(buffer.length() > 0) {
				buffer.append(string);
			}
			buffer.append(item);
		}
		return buffer.toString();
	}

Convert a stack trace into a string. Does not output every line of the stack trace, only those that appear to be useful.

Parameters:
t
Returns:
String version of the stack trace.
	public static String exceptionToString(Throwable tString separator) {
		String msg = t.getClass().getName() + ": " + t.getMessage() + separator;
		final StackTraceElement[] stackTrace = t.getStackTrace();
		boolean printedNonJavaLine = false;
		for (StackTraceElement element : stackTrace) {
			String className = element.getClassName();
			msg = msg + "   " + className + "." + element.getMethodName() + "():" + element.getLineNumber() + separator;
			if(className.startsWith("sun.") || className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("org.eclipse.jetty.")) {
				if(printedNonJavaLine) {
					break;
				}
else {
				printedNonJavaLine = true;
			}
		}
		return msg;
	}

Remove all whitespace from the start and end of a string. Removes space, cr, lf, and tab.

Parameters:
str the String to chomp a newline from, may be null
	public static String chomp(String str) {
		if(str == null || str.length() == 0) {
			return str;
		}
		int firstIdx = 0;
		int lastIdx = str.length() - 1;
		char c = str.charAt(lastIdx);
		while (c == '\n' || c == '\r' || c == '\t' || c == ' ') {
			if(lastIdx == 0) {
				break;
			}
			lastIdx--;
			c = str.charAt(lastIdx);
		}
		c = str.charAt(firstIdx);
		while (c == '\n' || c == '\r' || c == '\t' || c == ' ') {
			firstIdx++;
			if(firstIdx >= lastIdx) {
				break;
			}
			c = str.charAt(firstIdx);
		}
		return str.substring(firstIdxlastIdx + 1);
	}
New to GrepCode? Check out our FAQ X