public class

StringUtil

extends Object
java.lang.Object
   ↳ com.google.gdata.util.common.base.StringUtil

Class Overview

Some common string manipulation utilities.

Summary

Constants
String EMPTY_STRING
String LINE_BREAKS
String WHITE_SPACES
Fields
private static final Set<Character.UnicodeBlock> CJK_BLOCKS Unicode code blocks containing CJK characters.
private static final CharMatcher CONTROL_MATCHER
private static final String[] UNSAFE_TAGS
private static final Pattern characterReferencePattern
private static final Pattern dbSpecPattern
static Map<String, Character> escapeStrings
private static char[] hexChars
private static final Pattern htmlTagPattern
Public Methods
static String Collection2String(Collection<?> in, String separator)
This method is deprecated. Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.
static String Iterator2String(Iterator<?> it, String separator)
This method is deprecated. Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.
static boolean allAscii(String s)
Determines if a string contains only ascii characters
static void appendHexJavaScriptRepresentation(StringBuilder sb, char c)
Returns a javascript representation of the character in a hex escaped format.
static String arrayMap2String(Map<String, String[]> map, String keyValueDelim, String entryDelim)
Serializes a map
static String bytesToHexString(byte[] bytes, Character delimiter)
Convert a byte array to a hex-encoding string with the specified delimiter: "a3<delimiter>3b<delimiter>ff..."
static String bytesToHexString(byte[] bytes)
Convert a byte array to a hex-encoding string: "a33bff00..."
static String bytesToLatin1(byte[] ba)
Convert a byte array to a String using Latin-1 (aka ISO-8859-1) encoding.
static List<String> bytesToStringList(byte[] bytes)
Convert an array of bytes into a List of Strings using UTF-8.
static String bytesToUtf8(byte[] ba)
Convert a byte array to a String using UTF-8 encoding.
static String capitalize(String s)
Returns a string that is equivalent to the specified string with its first character converted to uppercase as by toUpperCase().
static String collapse(String str, String chars, String replacement)
Replaces any string of matched characters with the supplied string.
static String collapseWhitespace(String str)
Replaces any string of adjacent whitespace characters with the whitespace character " ".
static boolean containsCharRef(String s)
Determines if a string contains what looks like an html character reference.
static String convertEOLToCRLF(String input)
This method is deprecated. Please inline this method.
static String convertEOLToLF(String input)
Converts any instances of "\r" or "\r\n" style EOLs into "\n" (Line Feed).
static void copyStreams(InputStream in, OutputStream out)
Copy all data from in to out in 4096 byte chunks.
static String cropBetween(String in, String limit)
This removes characters between maching charLimit chars.
static String cropBetween(String in, char limit)
The old interface to cropBetween - using a single char limit
static int displayWidth(char ch)
Returns the approximate display width of the character, measured in units of ascii characters.
static int displayWidth(String s)
Returns the approximate display width of the string, measured in units of ascii characters.
static byte[] encodingToBytes(String str, String encoding)
Convert a String to a byte array using the specified encoding.
static boolean equals(String s1, String s2)
Compares two strings, guarding against nulls If both Strings are null we return true
static String expandShardNames(String dbSpecComponent)
static String fixedWidth(String str, int width)
Reformats the given string to a fixed width by inserting carriage returns and trimming unnecessary whitespace.
static String fixedWidth(String[] lines, int width)
Reformats the given array of lines to a fixed width by inserting carriage returns and trimming unnecessary whitespace.
static byte[] hexToBytes(String str)
Convert a string of hex digits to a byte array, with the first byte in the array being the MSB.
static String htmlEscape(String s)
Escapes special characters (& < > ") from a string so it can safely be included in an HTML document.
static String indent(String iString, int iIndentDepth)
Indents the given String per line.
static int indexOfChars(String str, String chars, int fromIndex)
Like String.indexOf() except that it will look for any of the characters in 'chars' (similar to C's strpbrk)
static int indexOfChars(String str, String chars)
Like String.indexOf() except that it will look for any of the characters in 'chars' (similar to C's strpbrk)
static String insertBreakingWhitespace(int lineLen, String original)
Inserts spaces every splitLen characters so that the string will wrap.
static boolean isCjk(char ch)
Determines if a character is a CJK ideograph or a character typically used only in CJK text.
static boolean isCjk(int codePoint)
Determines if a character is a CJK ideograph or a character typically used only in CJK text.
static boolean isCjk(String s)
Determines if a string is a CJK word.
static boolean isEmpty(String s)
Helper function for null and empty string testing.
static boolean isEmptyOrWhitespace(String s)
Helper function for null, empty, and whitespace string testing.
static boolean isHebrew(String s)
Determines if a string is a Hebrew word.
static boolean isHebrew(int codePoint)
Determines if a character is a Hebrew character.
static String javaEscape(String s)
We escape some characters in s to be able to insert strings into Java code
static String javaEscapeWithinAttribute(String s)
Escape a string so that it can be safely placed as value of an attribute.
static String javaScriptEscape(String s)
We escape some characters in s to be able to insert strings into JavaScript code.
static String javaScriptEscapeToAscii(String s)
We escape some characters in s to be able to insert strings into JavaScript code.
static String javaScriptUnescape(String s)
Undo escaping as performed in javaScriptEscape(.) Throws an IllegalArgumentException if the string contains bad escaping.
static String javaUtilRegexEscape(String s)
Escapes the special characters from a string so it can be used as part of a regex pattern.
static String join(Collection tokens, String delimiter)
This method is deprecated. Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.
static String join(Object[] tokens, String delimiter)
This method is deprecated. Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.
static String joinInts(int[] tokens, String delimiter)
Concatenates the given int[] array into one String, inserting a delimiter between each pair of elements.
static String joinLongs(long[] tokens, String delimiter)
Concatenates the given long[] array into one String, inserting a delimiter between each pair of elements.
static int lastIndexNotOf(String str, String chars, int fromIndex)
Finds the last index in str of a character not in the characters in 'chars' (similar to ANSI string.find_last_not_of).
static String lastToken(String s, String delimiter)
Splits s with delimiters in delimiter and returns the last token
static byte[] latin1ToBytes(String str)
Convert a String to a byte array using Latin-1 (aka ISO-8859-1) encoding.
static String list2String(Collection<?> in, String separator)
This method is deprecated. Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.
static <V> Map lowercaseKeys(Map<String, V> map)
Given a map, creates and returns a new map in which all keys are the lower-cased version of each key.
static String lstrip(String str)
This method is deprecated. ensure the string is not null and use CharMatcher.LEGACY_WHITESPACE.trimLeadingFrom(str); also consider whether you really want the legacy whitespace definition, or something more standard like WHITESPACE.
static String makeSafe(String s)
Helper function for making null strings safe for comparisons, etc.
static <K, V> String map2String(Map<K, V> in, String sepKey, String sepEntry)
This function concatenates the elements of a Map in a string with form "...
static String maskLeft(String s, int len, char mask_ch)
Returns a string consisting of "s", with each of the first "len" characters replaced by "mask_ch" character.
static String maskRight(String s, int len, char mask_ch)
Returns a string consisting of "s", with each of the last "len" characters replaces by "mask_ch" character.
static String megastrip(String str, boolean left, boolean right, String what)
This method is deprecated. ensure the string is not null and use
  • CharMatcher.anyOf(what).trimFrom(str) if left == true and right == true
  • CharMatcher.anyOf(what).trimLeadingFrom(str) if left == true and right == false
  • CharMatcher.anyOf(what).trimTrailingFrom(str) if left == false and right == true
static int numSharedChars(String str, String chars)
Counts the number of (not necessarily distinct) characters in the string that also happen to be in 'chars'
static String padLeft(String s, int len, char pad_ch)
Returns a string consisting of "s", plus enough copies of "pad_ch" on the left hand side to make the length of "s" equal to or greater than len (if "s" is already longer than "len", then "s" is returned).
static String padRight(String s, int len, char pad_ch)
Returns a string consisting of "s", plus enough copies of "pad_ch" on the right hand side to make the length of "s" equal to or greater than len (if "s" is already longer than "len", then "s" is returned).
static String[] parseDelimitedList(String list, char delimiter)
Parse a list of substrings separated by a given delimiter.
static String pythonEscape(String s)
We escape some characters in s to be able to make the string executable from a python string
static String regexEscape(String s)
Escapes the special characters from a string so it can be used as part of a regex pattern.
static String regexReplacementEscape(String s)
Escapes the '\' and '$' characters, which comprise the subset of regex characters that has special meaning in methods such as:
java.util.regex.Matcher.appendReplacement(sb, replacement);
java.lang.String.replaceAll(str, replacement);
Note that this method is offered in java version 1.5 as the method
java.util.regex.Matcher.quoteReplacement(String);
static String removeChars(String str, String oldchars)
Remove any occurrances of 'oldchars' in 'str'.
static String repeat(String sourceString, int factor)
Returns sourceString concatenated together 'factor' times.
static String replace(String str, String what, String with)
This method is deprecated. Please use replace(CharSequence, CharSequence).
static String replaceChars(String str, String oldchars, char newchar)
Like String.replace() except that it accepts any number of old chars.
static String replaceSmartQuotes(String str)
Replaces microsoft "smart quotes" (curly " and ') with their ascii counterparts.
static String retainAllChars(String str, String retainChars)
Removes all characters from 'str' that are not in 'retainChars'.
static String rstrip(String str)
This method is deprecated. ensure the string is not null and use CharMatcher.LEGACY_WHITESPACE.trimTrailingFrom(str); also consider whether you really want the legacy whitespace definition, or something more standard like WHITESPACE.
static String[] split(String str, String delims)
Split "str" by run of delimiters and return.
static String[] split(String str, String delims, boolean trimTokens)
Split "str" into tokens by delimiters and optionally remove white spaces from the splitted tokens.
static String[] splitAndTrim(String str, String delims)
Short hand for split(str, delims, true)
static int[] splitInts(String str)
Parse comma-separated list of ints and return as array.
static long[] splitLongs(String str)
Parse comma-separated list of longs and return as array.
static String stream2String(InputStream is, int maxLength)
Read a String of up to maxLength bytes from an InputStream
static Collection<String> string2Collection(String in, String delimiter, boolean doStrip, Collection<String> collection)
Converts a delimited string to a collection of strings.
static LinkedList<String> string2List(String in, String delimiter, boolean doStrip)
This converts a String to a list of strings by extracting the substrings between delimiter
static HashMap<String, String> string2Map(String in, String delimEntry, String delimKey, boolean doStripEntry)
This converts a string to a Map.
static Set string2Set(String in, String delimiter, boolean doStrip)
This converts a String to a Set of strings by extracting the substrings between delimiter
static String strip(String str)
strip - strips both ways
static String stripAndCollapse(String str)
Strip white spaces from both end, and collapse white spaces in the middle.
static String stripHtmlTags(String string)
Given a String, returns an equivalent String with all HTML tags stripped.
static String stripNonDigits(String str)
Strips all non-digit characters from a string.
static String stripPrefix(String str, String prefix)
Give me a string and a potential prefix, and I return the string following the prefix if the prefix matches, else null.
static String stripPrefixIgnoreCase(String str, String prefix)
Case insensitive version of stripPrefix.
static String toNullIfEmpty(String s)
Helper function for making empty strings into a null.
static String toNullIfEmptyOrWhitespace(String s)
Helper function for turning empty or whitespace strings into a null.
static String toString(long[] iArray)
static String toString(int[] iArray)
static String toString(String[] iArray)
static String toString(float[] iArray)
static String toString(Object[] obj)
static String toString(String s)
Returns the string, in single quotes, or "NULL".
static String toString(long[][] iArray)
static String toString(int[][] iArray)
static InputStream toUTF8InputStream(String str)
Replacement for deprecated StringBufferInputStream().
static String toUpperCase(String src)
Safely convert the string to uppercase.
static String unescapeCString(String s)
Unescape any C escape sequences (\n, \r, \\, \ooo, etc) and return the resulting string.
final static String unescapeHTML(String s)
Replace all the occurences of HTML escape strings with the respective characters.
static String unescapeMySQLString(String s)
Unescape any MySQL escape sequences.
static String unicodeEscape(String s)
Replaces each non-ascii character in s with its Unicode escape sequence \\uxxxx where xxxx is a hex number.
static byte[] utf8ToBytes(String str)
Convert a String to a byte array using UTF-8 encoding.
static String xmlCDataEscape(String s)
Escape a string that is meant to be embedded in a CDATA section.
static String xmlContentEscape(String s)
Escape a string for use inside as XML element content.
static String xmlEscape(String s)
Returns a form of "s" appropriate for including in an XML document, after escaping certain special characters (e.g.
static String xmlSingleQuotedEscape(String s)
Escape a string for use inside as XML single-quoted attributes.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final String EMPTY_STRING

Constant Value: ""

public static final String LINE_BREAKS

Constant Value: " "

public static final String WHITE_SPACES

Constant Value: "     "

Fields

private static final Set<Character.UnicodeBlock> CJK_BLOCKS

Unicode code blocks containing CJK characters.

private static final CharMatcher CONTROL_MATCHER

private static final String[] UNSAFE_TAGS

private static final Pattern characterReferencePattern

private static final Pattern dbSpecPattern

static Map<String, Character> escapeStrings

private static char[] hexChars

private static final Pattern htmlTagPattern

Public Methods

public static String Collection2String (Collection<?> in, String separator)

This method is deprecated.
Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.

This concatenates the elements of a collection in a string

Parameters
in - the collection that has to be conatenated
separator - a string to sepparate the elements from the list
Returns
  • String

public static String Iterator2String (Iterator<?> it, String separator)

This method is deprecated.
Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.

Parameters
it
separator

public static boolean allAscii (String s)

Determines if a string contains only ascii characters

Parameters
s

public static void appendHexJavaScriptRepresentation (StringBuilder sb, char c)

Returns a javascript representation of the character in a hex escaped format. Although this is a rather specific method, it is made public because it is also used by the JSCompiler.

Parameters
sb The buffer to which the hex representation should be appended.
c The character to be appended.

public static String arrayMap2String (Map<String, String[]> map, String keyValueDelim, String entryDelim)

Serializes a map

Parameters
map A map of String keys to arrays of String values
keyValueDelim Delimiter between keys and values
entryDelim Delimiter between entries
Returns
  • String A string containing a serialized representation of the contents of the map. e.g. arrayMap2String({"foo":["bar","bar2"],"foo1":["bar1"]}, "=", "&") returns "foo=bar&foo=bar2&foo1=bar1"

public static String bytesToHexString (byte[] bytes, Character delimiter)

Convert a byte array to a hex-encoding string with the specified delimiter: "a3<delimiter>3b<delimiter>ff..."

Parameters
bytes
delimiter

public static String bytesToHexString (byte[] bytes)

Convert a byte array to a hex-encoding string: "a33bff00..."

Parameters
bytes

public static String bytesToLatin1 (byte[] ba)

Convert a byte array to a String using Latin-1 (aka ISO-8859-1) encoding. Note: something is probably wrong if you're using this method. Either you're dealing with legacy code that doesn't support i18n or you're using a third-party library that only deals with Latin-1. New code should (almost) always uses UTF-8 encoding.

Parameters
ba
Returns
  • the decoded String or null if ba is null

public static List<String> bytesToStringList (byte[] bytes)

Convert an array of bytes into a List of Strings using UTF-8. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Can be used to parse the output of

Parameters
bytes The array to convert
Returns
  • A new mutable list containing the Strings in the input array. The list will be empty if bytes is empty or if it is null.

public static String bytesToUtf8 (byte[] ba)

Convert a byte array to a String using UTF-8 encoding.

Parameters
ba
Returns
  • the decoded String or null if ba is null

public static String capitalize (String s)

Returns a string that is equivalent to the specified string with its first character converted to uppercase as by toUpperCase(). The returned string will have the same value as the specified string if its first character is non-alphabetic, if its first character is already uppercase, or if the specified string is of length 0.

For example:

    capitalize("foo bar").equals("Foo bar");
    capitalize("2b or not 2b").equals("2b or not 2b")
    capitalize("Foo bar").equals("Foo bar");
    capitalize("").equals("");
 

Parameters
s The string whose first character is to be uppercased
Returns
  • a string equivalent to s with its first character converted to uppercase
Throws
NullPointerException if s is null

public static String collapse (String str, String chars, String replacement)

Replaces any string of matched characters with the supplied string.

This is a more general version of collapseWhitespace.

   E.g. collapse("hello     world", " ", "::")
   will return the following string: "hello::world"
 

Parameters
str The string you want to munge
chars All of the characters to be considered for munge
replacement The replacement string
Returns
  • String munged and replaced string.

public static String collapseWhitespace (String str)

Replaces any string of adjacent whitespace characters with the whitespace character " ".

Parameters
str The string you want to munge
Returns
  • String with no more excessive whitespace!
See Also
  • collapse

public static boolean containsCharRef (String s)

Determines if a string contains what looks like an html character reference. Useful for deciding whether unescaping is necessary.

Parameters
s

public static String convertEOLToCRLF (String input)

This method is deprecated.
Please inline this method.

Parameters
input

public static String convertEOLToLF (String input)

Converts any instances of "\r" or "\r\n" style EOLs into "\n" (Line Feed).

Parameters
input

public static void copyStreams (InputStream in, OutputStream out)

Copy all data from in to out in 4096 byte chunks.

Parameters
in
out
Throws
IOException

public static String cropBetween (String in, String limit)

This removes characters between maching charLimit chars. For example cropBetween("ab^cd^ef^gh^hi", '^') will return "abefhi" It will consider squences of 2 charLimit as one charLimit in the output

Parameters
in - the string to process
limit - the limit of the string(s) to remove
Returns
  • String - the cropped string

public static String cropBetween (String in, char limit)

The old interface to cropBetween - using a single char limit

Parameters
in
limit

public static int displayWidth (char ch)

Returns the approximate display width of the character, measured in units of ascii characters. This method should err on the side of caution. By default, characters are assumed to have width 2; this covers CJK ideographs, various symbols and miscellaneous weird scripts. Given below are some Unicode ranges for which it seems safe to assume that no character is substantially wider than an ascii character: - Latin, extended Latin, even more extended Latin. - Greek, extended Greek, Cyrillic. - Some symbols (including currency symbols) and punctuation. - Half-width Katakana and Hangul. - Hebrew - Thai Characters in these ranges are given a width of 1. IMPORTANT: this function has an analog in strutil.cc named UnicodeCharWidth, which needs to be updated if you change the implementation here.

Parameters
ch

public static int displayWidth (String s)

Returns the approximate display width of the string, measured in units of ascii characters.

Parameters
s
See Also
  • displayWidth(char)

public static byte[] encodingToBytes (String str, String encoding)

Convert a String to a byte array using the specified encoding.

Parameters
str
encoding The encoding to use
Returns
  • the encoded byte array or null if str is null

public static boolean equals (String s1, String s2)

Compares two strings, guarding against nulls If both Strings are null we return true

Parameters
s1
s2

public static String expandShardNames (String dbSpecComponent)

Parameters
dbSpecComponent A single component of a DBDescriptor spec (e.g. the host or database component). The expected format of the string is:
(prefix){(digits),(digits)}(suffix)
Returns
  • a shard expansion of the given String. Note that unless the pattern is matched exactly, no expansion is performed and the original string is returned unaltered. For example, 'db{0,1}.adz' is expanded into 'db0.adz, db1.adz'. Note that this method is added to StringUtil instead of DBDescriptor to better encapsulate the choice of regexp implementation.
Throws
IllegalArgumentException if the string does not parse.
IllegalStateException

public static String fixedWidth (String str, int width)

Reformats the given string to a fixed width by inserting carriage returns and trimming unnecessary whitespace.

Parameters
str The string to format
width The fixed width (in characters)

public static String fixedWidth (String[] lines, int width)

Reformats the given array of lines to a fixed width by inserting carriage returns and trimming unnecessary whitespace.

Parameters
lines - array of lines to format
width - the fixed width (in characters)

public static byte[] hexToBytes (String str)

Convert a string of hex digits to a byte array, with the first byte in the array being the MSB. The string passed in should be just the raw digits (upper or lower case), with no leading or trailing characters (like '0x' or 'h'). An odd number of characters is supported. If the string is empty, an empty array will be returned. This is significantly faster than using new BigInteger(str, 16).toByteArray(); especially with larger strings. Here are the results of some microbenchmarks done on a P4 2.8GHz 2GB RAM running linux 2.4.22-gg11 and JDK 1.5 with an optimized build: String length hexToBytes (usec) BigInteger ----------------------------------------------------- 16 0.570 1.43 256 8.21 44.4 1024 32.8 526 16384 546 121000

Parameters
str

public static String htmlEscape (String s)

Escapes special characters (& < > ") from a string so it can safely be included in an HTML document. (same as xmlEscape except that htmlEscape does not escape the apostrophe character).

Parameters
s

public static String indent (String iString, int iIndentDepth)

Indents the given String per line.

Parameters
iString The string to indent.
iIndentDepth The depth of the indentation.
Returns
  • The indented string.

public static int indexOfChars (String str, String chars, int fromIndex)

Like String.indexOf() except that it will look for any of the characters in 'chars' (similar to C's strpbrk)

Parameters
str
chars
fromIndex

public static int indexOfChars (String str, String chars)

Like String.indexOf() except that it will look for any of the characters in 'chars' (similar to C's strpbrk)

Parameters
str
chars

public static String insertBreakingWhitespace (int lineLen, String original)

Inserts spaces every splitLen characters so that the string will wrap.

Parameters
lineLen The length of the substrings to separate with spaces.
original The original String
Returns
  • original String with spaces inserted every lineLen characters.

public static boolean isCjk (char ch)

Determines if a character is a CJK ideograph or a character typically used only in CJK text. Note: This function cannot handle supplementary characters. To handle all Unicode characters, including supplementary characters, use the function isCjk(int).

Parameters
ch

public static boolean isCjk (int codePoint)

Determines if a character is a CJK ideograph or a character typically used only in CJK text.

Parameters
codePoint

public static boolean isCjk (String s)

Determines if a string is a CJK word. A string is considered to be CJK if isCjk(char) is true for any of its characters.

Parameters
s

public static boolean isEmpty (String s)

Helper function for null and empty string testing.

Parameters
s
Returns
  • true iff s == null or s.equals("");

public static boolean isEmptyOrWhitespace (String s)

Helper function for null, empty, and whitespace string testing.

Parameters
s
Returns
  • true if s == null or s.equals("") or s contains only whitespace characters.

public static boolean isHebrew (String s)

Determines if a string is a Hebrew word. A string is considered to be a Hebrew word if isHebrew(int) is true for any of its characters.

Parameters
s

public static boolean isHebrew (int codePoint)

Determines if a character is a Hebrew character.

Parameters
codePoint

public static String javaEscape (String s)

We escape some characters in s to be able to insert strings into Java code

Parameters
s

public static String javaEscapeWithinAttribute (String s)

Escape a string so that it can be safely placed as value of an attribute. This is essentially similar to the javaEscape(java.lang.String) except that it escapes double quote to the HTML literal &quot;. This is to prevent the double quote from being interpreted as the character closing the attribute.

Parameters
s

public static String javaScriptEscape (String s)

We escape some characters in s to be able to insert strings into JavaScript code. Also, make sure that we don't write out --> or

Parameters
s

public static String javaScriptEscapeToAscii (String s)

We escape some characters in s to be able to insert strings into JavaScript code. Also, make sure that we don't write out --> or </scrip, which may close a script tag. Turns all non-ascii characters into ASCII javascript escape sequences (eg ?)

Parameters
s

public static String javaScriptUnescape (String s)

Undo escaping as performed in javaScriptEscape(.) Throws an IllegalArgumentException if the string contains bad escaping.

Parameters
s

public static String javaUtilRegexEscape (String s)

Escapes the special characters from a string so it can be used as part of a regex pattern. This method is for use on regexes in the flavor of the java.util.regex package. This method should be removed when we move to the java version 1.5 (Tiger) release, since that release gives us a literal regex flag as well as a quote method to produce literal regexes.

Parameters
s

public static String join (Collection tokens, String delimiter)

This method is deprecated.
Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.

Same as join(Object[], String), but takes a Collection instead.

Parameters
tokens
delimiter

public static String join (Object[] tokens, String delimiter)

This method is deprecated.
Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.

Concatenates the String representations of the elements of a String[] array into one String, and inserts a delimiter between each pair of elements.

This includes the String[] case, because if s is a String, then s.toString() returns s.

Parameters
tokens
delimiter

public static String joinInts (int[] tokens, String delimiter)

Concatenates the given int[] array into one String, inserting a delimiter between each pair of elements.

Parameters
tokens
delimiter

public static String joinLongs (long[] tokens, String delimiter)

Concatenates the given long[] array into one String, inserting a delimiter between each pair of elements.

Parameters
tokens
delimiter

public static int lastIndexNotOf (String str, String chars, int fromIndex)

Finds the last index in str of a character not in the characters in 'chars' (similar to ANSI string.find_last_not_of). Returns -1 if no such character can be found.

Parameters
str
chars
fromIndex

public static String lastToken (String s, String delimiter)

Splits s with delimiters in delimiter and returns the last token

Parameters
s
delimiter

public static byte[] latin1ToBytes (String str)

Convert a String to a byte array using Latin-1 (aka ISO-8859-1) encoding. If any character in the String is not Latin-1 (meaning it's high 8 bits are not all zero), then the returned byte array will contain garbage. Therefore, only use this if you know all your characters are within Latin-1. Note: something is probably wrong if you're using this method. Either you're dealing with legacy code that doesn't support i18n or you're using a third-party library that only deals with Latin-1. New code should (almost) always uses UTF-8 encoding.

Parameters
str
Returns
  • the encoded byte array or null if str is null

public static String list2String (Collection<?> in, String separator)

This method is deprecated.
Please use But note that Join does not consider null elements to be equivalent to the empty string, as this method does.

Lots of people called list2String when in fact it was implemented as Collection2String. I added Collection2String as a new function and am leaving the list2String function signature here so it can continue to be

Parameters
in
separator

public static Map lowercaseKeys (Map<String, V> map)

Given a map, creates and returns a new map in which all keys are the lower-cased version of each key.

Parameters
map A map containing String keys to be lowercased
Throws
IllegalArgumentException if the map contains duplicate string keys after lower casing

public static String lstrip (String str)

This method is deprecated.
ensure the string is not null and use CharMatcher.LEGACY_WHITESPACE.trimLeadingFrom(str); also consider whether you really want the legacy whitespace definition, or something more standard like WHITESPACE.

lstrip - strips spaces from left

Parameters
str What to strip
Returns
  • String the striped string

public static String makeSafe (String s)

Helper function for making null strings safe for comparisons, etc.

Parameters
s
Returns
  • (s == null) ? "" : s;

public static String map2String (Map<K, V> in, String sepKey, String sepEntry)

This function concatenates the elements of a Map in a string with form "..."

Parameters
in - the map to be converted
sepKey - the separator to put between key and value
sepEntry - the separator to put between map entries
Returns
  • String

public static String maskLeft (String s, int len, char mask_ch)

Returns a string consisting of "s", with each of the first "len" characters replaced by "mask_ch" character.

Parameters
s
len
mask_ch

public static String maskRight (String s, int len, char mask_ch)

Returns a string consisting of "s", with each of the last "len" characters replaces by "mask_ch" character.

Parameters
s
len
mask_ch

public static String megastrip (String str, boolean left, boolean right, String what)

This method is deprecated.
ensure the string is not null and use

  • CharMatcher.anyOf(what).trimFrom(str) if left == true and right == true
  • CharMatcher.anyOf(what).trimLeadingFrom(str) if left == true and right == false
  • CharMatcher.anyOf(what).trimTrailingFrom(str) if left == false and right == true

This is a both way strip

Parameters
str The string to strip
left Strip from left
right Strip from right
what Character(s) to strip
Returns
  • the stripped string

public static int numSharedChars (String str, String chars)

Counts the number of (not necessarily distinct) characters in the string that also happen to be in 'chars'

Parameters
str
chars

public static String padLeft (String s, int len, char pad_ch)

Returns a string consisting of "s", plus enough copies of "pad_ch" on the left hand side to make the length of "s" equal to or greater than len (if "s" is already longer than "len", then "s" is returned).

Parameters
s
len
pad_ch

public static String padRight (String s, int len, char pad_ch)

Returns a string consisting of "s", plus enough copies of "pad_ch" on the right hand side to make the length of "s" equal to or greater than len (if "s" is already longer than "len", then "s" is returned).

Parameters
s
len
pad_ch

public static String[] parseDelimitedList (String list, char delimiter)

Parse a list of substrings separated by a given delimiter. The delimiter can also appear in substrings (just double them): parseDelimitedString("this|is", '|') returns ["this","is"] parseDelimitedString("this||is", '|') returns ["this|is"]

Parameters
list String containing delimited substrings
delimiter Delimiter (anything except ' ' is allowed)
Returns
  • String[] A String array of parsed substrings

public static String pythonEscape (String s)

We escape some characters in s to be able to make the string executable from a python string

Parameters
s

public static String regexEscape (String s)

Escapes the special characters from a string so it can be used as part of a regex pattern. This method is for use on gnu.regexp style regular expressions.

Parameters
s

public static String regexReplacementEscape (String s)

Escapes the '\' and '$' characters, which comprise the subset of regex characters that has special meaning in methods such as:

java.util.regex.Matcher.appendReplacement(sb, replacement);
java.lang.String.replaceAll(str, replacement);
Note that this method is offered in java version 1.5 as the method
java.util.regex.Matcher.quoteReplacement(String);

Parameters
s

public static String removeChars (String str, String oldchars)

Remove any occurrances of 'oldchars' in 'str'. Example: removeChars("Hello, world!", ",!") returns "Hello world"

Parameters
str
oldchars

public static String repeat (String sourceString, int factor)

Returns sourceString concatenated together 'factor' times.

Parameters
sourceString The string to repeat
factor The number of times to repeat it.

public static String replace (String str, String what, String with)

This method is deprecated.
Please use replace(CharSequence, CharSequence).

This replaces the occurances of 'what' in 'str' with 'with'

Parameters
str - the string o process
what - to replace
with - replace with this
Returns
  • String str whete 'what' was repalced with 'with'

public static String replaceChars (String str, String oldchars, char newchar)

Like String.replace() except that it accepts any number of old chars. Replaces any occurrances of 'oldchars' in 'str' with 'newchar'. Example: replaceChars("Hello, world!", "H,!", ' ') returns " ello world "

Parameters
str
oldchars
newchar

public static String replaceSmartQuotes (String str)

Replaces microsoft "smart quotes" (curly " and ') with their ascii counterparts.

Parameters
str

public static String retainAllChars (String str, String retainChars)

Removes all characters from 'str' that are not in 'retainChars'. Example: retainAllChars("Hello, world!", "lo") returns "llool"

Parameters
str
retainChars

public static String rstrip (String str)

This method is deprecated.
ensure the string is not null and use CharMatcher.LEGACY_WHITESPACE.trimTrailingFrom(str); also consider whether you really want the legacy whitespace definition, or something more standard like WHITESPACE.

rstrip - strips spaces from right

Parameters
str What to strip
Returns
  • String the striped string

public static String[] split (String str, String delims)

Split "str" by run of delimiters and return.

Parameters
str
delims

public static String[] split (String str, String delims, boolean trimTokens)

Split "str" into tokens by delimiters and optionally remove white spaces from the splitted tokens.

Parameters
str
delims
trimTokens If true, then trim the tokens

public static String[] splitAndTrim (String str, String delims)

Short hand for split(str, delims, true)

Parameters
str
delims

public static int[] splitInts (String str)

Parse comma-separated list of ints and return as array.

Parameters
str
Throws
IllegalArgumentException

public static long[] splitLongs (String str)

Parse comma-separated list of longs and return as array.

Parameters
str
Throws
IllegalArgumentException

public static String stream2String (InputStream is, int maxLength)

Read a String of up to maxLength bytes from an InputStream

Parameters
is Input stream
maxLength Max number of bytes to read from "is". If this is -1, we read everything.
Returns
  • String up to maxLength bytes, read from "is"
Throws
IOException

public static Collection<String> string2Collection (String in, String delimiter, boolean doStrip, Collection<String> collection)

Converts a delimited string to a collection of strings. Substrings between delimiters are extracted from the string and added to a collection that is provided by the caller.

Parameters
in The delimited input string to process
delimiter The string delimiting entries in the input string.
doStrip
collection The collection to which the strings will be added. If null, a new List will be created.
Returns
  • The collection to which the substrings were added. This is syntactic sugar to allow call chaining.

public static LinkedList<String> string2List (String in, String delimiter, boolean doStrip)

This converts a String to a list of strings by extracting the substrings between delimiter

Parameters
in - what to process
delimiter - the delimiting string
doStrip - to strip the substrings before adding to the list
Returns
  • LinkedList

public static HashMap<String, String> string2Map (String in, String delimEntry, String delimKey, boolean doStripEntry)

This converts a string to a Map. It will first split the string into entries using delimEntry. Then each entry is split into a key and a value using delimKey. By default we strip the keys. Use doStripEntry to strip also the entries

Parameters
in - the string to be processed
delimEntry - delimiter for the entries
delimKey - delimiter between keys and values
doStripEntry - strip entries before inserting in the map
Returns
  • HashMap

public static Set string2Set (String in, String delimiter, boolean doStrip)

This converts a String to a Set of strings by extracting the substrings between delimiter

Parameters
in - what to process
delimiter - the delimiting string
doStrip - to strip the substrings before adding to the list
Returns
  • Set

public static String strip (String str)

strip - strips both ways

Parameters
str What to strip
Returns
  • String the striped string

public static String stripAndCollapse (String str)

Strip white spaces from both end, and collapse white spaces in the middle.

Parameters
str What to strip
Returns
  • String the striped and collapsed string

public static String stripHtmlTags (String string)

Given a String, returns an equivalent String with all HTML tags stripped. Note that HTML entities, such as "&amp;" will still be preserved.

Parameters
string

public static String stripNonDigits (String str)

Strips all non-digit characters from a string. The resulting string will only contain characters for which isDigit() returns true.

Parameters
str The string to strip
Returns
  • a string consisting of digits only, or an empty string

public static String stripPrefix (String str, String prefix)

Give me a string and a potential prefix, and I return the string following the prefix if the prefix matches, else null. Analogous to the c++ functions strprefix and var_strprefix.

Parameters
str
prefix

public static String stripPrefixIgnoreCase (String str, String prefix)

Case insensitive version of stripPrefix. Analogous to the c++ functions strcaseprefix and var_strcaseprefix.

Parameters
str
prefix

public static String toNullIfEmpty (String s)

Helper function for making empty strings into a null.

Parameters
s
Returns
  • null if s is zero length. otherwise, returns s.

public static String toNullIfEmptyOrWhitespace (String s)

Helper function for turning empty or whitespace strings into a null.

Parameters
s
Returns
  • null if s is zero length or if s contains only whitespace characters. otherwise, returns s.

public static String toString (long[] iArray)

Parameters
iArray
Returns
  • a string representation of the given native array.

public static String toString (int[] iArray)

Parameters
iArray
Returns
  • a string representation of the given native array

public static String toString (String[] iArray)

Parameters
iArray
Returns
  • a string representation of the given array.

public static String toString (float[] iArray)

Parameters
iArray
Returns
  • a string representation of the given native array.

public static String toString (Object[] obj)

Parameters
obj
Returns
  • a String representation of the given object array. The strings are obtained by calling toString() on the underlying objects.

public static String toString (String s)

Returns the string, in single quotes, or "NULL". Intended only for logging.

Parameters
s - the string
Returns
  • the string, in single quotes, or the string "null" if it's null.

public static String toString (long[][] iArray)

Parameters
iArray
Returns
  • a string representation of the given native array.

public static String toString (int[][] iArray)

Parameters
iArray
Returns
  • a string representation of the given native array

public static InputStream toUTF8InputStream (String str)

Replacement for deprecated StringBufferInputStream(). Instead of: InputStream is = new StringBuilderInputStream(str); do: InputStream is = StringUtil.toUTF8InputStream(str);

Parameters
str

public static String toUpperCase (String src)

Safely convert the string to uppercase.

Parameters
src
Returns
  • upper case representation of the String; or null if the input string is null.

public static String unescapeCString (String s)

Unescape any C escape sequences (\n, \r, \\, \ooo, etc) and return the resulting string.

Parameters
s

public static final String unescapeHTML (String s)

Replace all the occurences of HTML escape strings with the respective characters.

Parameters
s A String value
Returns
  • a String value

public static String unescapeMySQLString (String s)

Unescape any MySQL escape sequences. See MySQL language reference Chapter 6 at http://www.mysql.com/doc/. This function will not work for other SQL-like dialects.

Parameters
s String to unescape, with the surrounding quotes.
Returns
  • unescaped string, without the surrounding quotes.
Throws
IllegalArgumentException if s is not a valid MySQL string.

public static String unicodeEscape (String s)

Replaces each non-ascii character in s with its Unicode escape sequence \\uxxxx where xxxx is a hex number. Existing escape sequences won't be affected.

Parameters
s

public static byte[] utf8ToBytes (String str)

Convert a String to a byte array using UTF-8 encoding.

Parameters
str
Returns
  • the encoded byte array or null if str is null

public static String xmlCDataEscape (String s)

Escape a string that is meant to be embedded in a CDATA section. The returned string is guaranteed to be valid CDATA content. The syntax of CDATA sections is the following:

<[!CDATA[...]]>
The only invalid character sequence in a CDATA tag is "]]>". If this sequence is present in the input string, we replace it by closing the current CDATA field, then write ']]&gt;', then reopen a new CDATA section.

Parameters
s

public static String xmlContentEscape (String s)

Escape a string for use inside as XML element content. This escapes less-than and ampersand, only.

Parameters
s

public static String xmlEscape (String s)

Returns a form of "s" appropriate for including in an XML document, after escaping certain special characters (e.g. '&' => '&', etc.)

Parameters
s

public static String xmlSingleQuotedEscape (String s)

Escape a string for use inside as XML single-quoted attributes. This escapes less-than, single-quote, ampersand, and (not strictly necessary) newlines.

Parameters
s