org.drools.core.util
Class StringUtils

java.lang.Object
  extended by org.drools.core.util.StringUtils

public class StringUtils
extends Object

Ripped form commons StringUtil, unless specified:

Operations on String that are null safe.

The StringUtils class defines certain words related to String handling.

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.

Since:
1.0
Version:
$Id$
See Also:
String

Nested Class Summary
static class StringUtils.SIMILARITY_STRATS
           
 
Field Summary
static String EMPTY
          The empty String "".
static String[] EMPTY_STRING_ARRAY
          An empty immutable String array.
static int INDEX_NOT_FOUND
          Represents a failed index search.
 
Constructor Summary
StringUtils()
          StringUtils instances should NOT be constructed in standard programming.
 
Method Summary
static String applyRelativePath(String path, String relativePath)
          Apply the given relative path to the given path, assuming standard Java folder separation (i.e. "/" separators);
static String cleanPath(String path)
          Normalize the path by suppressing sequences like "path/.." and inner simple dots.
static String collectionToDelimitedString(Collection coll, String delim)
          Convenience method to return a Collection as a delimited (e.g.
static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix)
          Convenience method to return a Collection as a delimited (e.g.
static String deleteAny(String inString, String charsToDelete)
          Delete any character in a given String.
static String[] delimitedListToStringArray(String str, String delimiter)
          Take a String which is a delimited list and convert it to a String array.
static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete)
          Take a String which is a delimited list and convert it to a String array.
static String escapeXmlString(String string)
           
static String extractFirstIdentifier(String string, int start)
           
static int extractFirstIdentifier(String string, StringBuilder builder, int start)
           
static int findEndMethodArgs(CharSequence string, int startMethodArgs)
           
static String generateUUID()
           
static int indexOfOutOfQuotes(String str, char searched)
           
static int indexOfOutOfQuotes(String str, String searched)
           
static boolean isEmpty(CharSequence str)
          Checks if a String is empty ("") or null.
static boolean isIdentifier(String expr)
           
static String padding(int repeat, char padChar)
          Returns padding using the specified delimiter repeated to a given length.
static String readFileAsString(Reader reader)
           
static String repeat(String str, int repeat)
          Repeat a String repeat times to form a new String.
static String replace(String inString, String oldPattern, String newPattern)
          Replace all occurences of a substring within a string with another string.
static int skipBlanks(String string, int start)
           
static String[] split(String str)
          Splits the provided text into an array, using whitespace as the separator.
static String[] split(String str, char separatorChar)
          Splits the provided text into an array, separator specified.
static String[] split(String str, String separatorChars)
          Splits the provided text into an array, separators specified.
static String[] split(String str, String separatorChars, int max)
          Splits the provided text into an array with a maximum length, separators specified.
static List<String> splitArgumentsList(CharSequence string)
           
static String[] splitPreserveAllTokens(String str)
          Splits the provided text into an array, using whitespace as the separator, preserving all tokens, including empty tokens created by adjacent separators.
static String[] splitPreserveAllTokens(String str, char separatorChar)
          Splits the provided text into an array, separator specified, preserving all tokens, including empty tokens created by adjacent separators.
static String[] splitPreserveAllTokens(String str, String separatorChars)
          Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.
static String[] splitPreserveAllTokens(String str, String separatorChars, int max)
          Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.
static List<String> splitStatements(CharSequence string)
           
static double stringSimilarity(String s1, String s2, StringUtils.SIMILARITY_STRATS method)
           
static String toString(BufferedReader reader)
           
static String toString(InputStream is)
           
static String toString(Reader reader)
           
static String[] toStringArray(Collection collection)
          Copy the given Collection into a String array.
static URI toURI(String location)
           
static String ucFirst(String name)
           
static String unescapeJava(String str)
          Unescapes any Java literals found in the String.
static void unescapeJava(Writer out, String str)
          Unescapes any Java literals found in the String to a Writer.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

EMPTY_STRING_ARRAY

public static final String[] EMPTY_STRING_ARRAY
An empty immutable String array.


EMPTY

public static final String EMPTY
The empty String "".

Since:
2.0
See Also:
Constant Field Values

INDEX_NOT_FOUND

public static final int INDEX_NOT_FOUND
Represents a failed index search.

Since:
2.1
See Also:
Constant Field Values
Constructor Detail

StringUtils

public StringUtils()

StringUtils instances should NOT be constructed in standard programming. Instead, the class should be used as StringUtils.trim(" foo ");.

This constructor is public to permit tools that require a JavaBean instance to operate.

Method Detail

ucFirst

public static String ucFirst(String name)

isEmpty

public static boolean isEmpty(CharSequence str)

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().

Parameters:
str - the String to check, may be null
Returns:
true if the String is empty or null

repeat

public static String repeat(String str,
                            int repeat)

Repeat a String repeat times to form a new String.

 StringUtils.repeat(null, 2) = null
 StringUtils.repeat("", 0)   = ""
 StringUtils.repeat("", 2)   = ""
 StringUtils.repeat("a", 3)  = "aaa"
 StringUtils.repeat("ab", 2) = "abab"
 StringUtils.repeat("a", -2) = ""
 

Parameters:
str - the String to repeat, may be null
repeat - number of times to repeat str, negative treated as zero
Returns:
a new String consisting of the original String repeated, null if null String input

split

public static String[] split(String str)

Splits the provided text into an array, using whitespace as the separator. Whitespace is defined by Character.isWhitespace(char).

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

A null input String returns null.

 StringUtils.split(null)       = null
 StringUtils.split("")         = []
 StringUtils.split("abc def")  = ["abc", "def"]
 StringUtils.split("abc  def") = ["abc", "def"]
 StringUtils.split(" abc ")    = ["abc"]
 

Parameters:
str - the String to parse, may be null
Returns:
an array of parsed Strings, null if null String input

split

public static String[] split(String str,
                             char separatorChar)

Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a\tb\nc", null) = ["a", "b", "c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
 

Parameters:
str - the String to parse, may be null
separatorChar - the character used as the delimiter, null splits on whitespace
Returns:
an array of parsed Strings, null if null String input
Since:
2.0

split

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

Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

A null input String returns null. A null separatorChars splits on whitespace.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("abc def", null) = ["abc", "def"]
 StringUtils.split("abc def", " ")  = ["abc", "def"]
 StringUtils.split("abc  def", " ") = ["abc", "def"]
 StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
 

Parameters:
str - the String to parse, may be null
separatorChars - the characters used as the delimiters, null splits on whitespace
Returns:
an array of parsed Strings, null if null String input

split

public static String[] split(String str,
                             String separatorChars,
                             int max)

Splits the provided text into an array with a maximum length, separators specified.

The separator is not included in the returned String array. Adjacent separators are treated as one separator.

A null input String returns null. A null separatorChars splits on whitespace.

If more than min delimited substrings are found, the last returned string includes all characters after the first min - 1 returned strings (including separator characters).

 StringUtils.split(null, *, *)            = null
 StringUtils.split("", *, *)              = []
 StringUtils.split("ab de fg", null, 0)   = ["ab", "cd", "ef"]
 StringUtils.split("ab   de fg", null, 0) = ["ab", "cd", "ef"]
 StringUtils.split("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
 StringUtils.split("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
 

Parameters:
str - the String to parse, may be null
separatorChars - the characters used as the delimiters, null splits on whitespace
min - the maximum number of elements to include in the array. A zero or negative value implies no limit
Returns:
an array of parsed Strings, null if null String input

splitPreserveAllTokens

public static String[] splitPreserveAllTokens(String str)

Splits the provided text into an array, using whitespace as the separator, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer. Whitespace is defined by Character.isWhitespace(char).

The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.

A null input String returns null.

 StringUtils.splitPreserveAllTokens(null)       = null
 StringUtils.splitPreserveAllTokens("")         = []
 StringUtils.splitPreserveAllTokens("abc def")  = ["abc", "def"]
 StringUtils.splitPreserveAllTokens("abc  def") = ["abc", "", "def"]
 StringUtils.splitPreserveAllTokens(" abc ")    = ["", "abc", ""]
 

Parameters:
str - the String to parse, may be null
Returns:
an array of parsed Strings, null if null String input
Since:
2.1

splitPreserveAllTokens

public static String[] splitPreserveAllTokens(String str,
                                              char separatorChar)

Splits the provided text into an array, separator specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.

The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.

A null input String returns null.

 StringUtils.splitPreserveAllTokens(null, *)         = null
 StringUtils.splitPreserveAllTokens("", *)           = []
 StringUtils.splitPreserveAllTokens("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.splitPreserveAllTokens("a..b.c", '.')   = ["a", "", "b", "c"]
 StringUtils.splitPreserveAllTokens("a:b:c", '.')    = ["a:b:c"]
 StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
 StringUtils.splitPreserveAllTokens("a b c", ' ')    = ["a", "b", "c"]
 StringUtils.splitPreserveAllTokens("a b c ", ' ')   = ["a", "b", "c", ""]
 StringUtils.splitPreserveAllTokens("a b c  ", ' ')   = ["a", "b", "c", "", ""]
 StringUtils.splitPreserveAllTokens(" a b c", ' ')   = ["", a", "b", "c"]
 StringUtils.splitPreserveAllTokens("  a b c", ' ')  = ["", "", a", "b", "c"]
 StringUtils.splitPreserveAllTokens(" a b c ", ' ')  = ["", a", "b", "c", ""]
 

Parameters:
str - the String to parse, may be null
separatorChar - the character used as the delimiter, null splits on whitespace
Returns:
an array of parsed Strings, null if null String input
Since:
2.1

splitPreserveAllTokens

public static String[] splitPreserveAllTokens(String str,
                                              String separatorChars)

Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.

The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.

A null input String returns null. A null separatorChars splits on whitespace.

 StringUtils.splitPreserveAllTokens(null, *)           = null
 StringUtils.splitPreserveAllTokens("", *)             = []
 StringUtils.splitPreserveAllTokens("abc def", null)   = ["abc", "def"]
 StringUtils.splitPreserveAllTokens("abc def", " ")    = ["abc", "def"]
 StringUtils.splitPreserveAllTokens("abc  def", " ")   = ["abc", "", def"]
 StringUtils.splitPreserveAllTokens("ab:cd:ef", ":")   = ["ab", "cd", "ef"]
 StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":")  = ["ab", "cd", "ef", ""]
 StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
 StringUtils.splitPreserveAllTokens("ab::cd:ef", ":")  = ["ab", "", cd", "ef"]
 StringUtils.splitPreserveAllTokens(":cd:ef", ":")     = ["", cd", "ef"]
 StringUtils.splitPreserveAllTokens("::cd:ef", ":")    = ["", "", cd", "ef"]
 StringUtils.splitPreserveAllTokens(":cd:ef:", ":")    = ["", cd", "ef", ""]
 

Parameters:
str - the String to parse, may be null
separatorChars - the characters used as the delimiters, null splits on whitespace
Returns:
an array of parsed Strings, null if null String input
Since:
2.1

splitPreserveAllTokens

public static String[] splitPreserveAllTokens(String str,
                                              String separatorChars,
                                              int max)

Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.

The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. Adjacent separators are treated as one separator.

A null input String returns null. A null separatorChars splits on whitespace.

If more than min delimited substrings are found, the last returned string includes all characters after the first min - 1 returned strings (including separator characters).

 StringUtils.splitPreserveAllTokens(null, *, *)            = null
 StringUtils.splitPreserveAllTokens("", *, *)              = []
 StringUtils.splitPreserveAllTokens("ab de fg", null, 0)   = ["ab", "cd", "ef"]
 StringUtils.splitPreserveAllTokens("ab   de fg", null, 0) = ["ab", "cd", "ef"]
 StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
 StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
 StringUtils.splitPreserveAllTokens("ab   de fg", null, 2) = ["ab", "  de fg"]
 StringUtils.splitPreserveAllTokens("ab   de fg", null, 3) = ["ab", "", " de fg"]
 StringUtils.splitPreserveAllTokens("ab   de fg", null, 4) = ["ab", "", "", "de fg"]
 

Parameters:
str - the String to parse, may be null
separatorChars - the characters used as the delimiters, null splits on whitespace
min - the maximum number of elements to include in the array. A zero or negative value implies no limit
Returns:
an array of parsed Strings, null if null String input
Since:
2.1

padding

public static String padding(int repeat,
                             char padChar)
                      throws IndexOutOfBoundsException

Returns padding using the specified delimiter repeated to a given length.

 StringUtils.padding(0, 'e')  = ""
 StringUtils.padding(3, 'e')  = "eee"
 StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
 

Note: this method doesn't not support padding with Unicode Supplementary Characters as they require a pair of chars to be represented. If you are needing to support full I18N of your applications consider using repeat(String, int) instead.

Parameters:
repeat - number of times to repeat delim
padChar - character to repeat
Returns:
String with repeated character
Throws:
IndexOutOfBoundsException - if repeat < 0
See Also:
repeat(String, int)

readFileAsString

public static String readFileAsString(Reader reader)
Parameters:
filePath - the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded

unescapeJava

public static String unescapeJava(String str)

Unescapes any Java literals found in the String. For example, it will turn a sequence of '\' and 'n' into a newline character, unless the '\' is preceded by another '\'.

Parameters:
str - the String to unescape, may be null
Returns:
a new unescaped String, null if null string input

unescapeJava

public static void unescapeJava(Writer out,
                                String str)
                         throws IOException

Unescapes any Java literals found in the String to a Writer.

For example, it will turn a sequence of '\' and 'n' into a newline character, unless the '\' is preceded by another '\'.

A null string input has no effect.

Parameters:
out - the Writer used to output unescaped characters
str - the String to unescape, may be null
Throws:
IllegalArgumentException - if the Writer is null
IOException - if error occurs on underlying Writer

applyRelativePath

public static String applyRelativePath(String path,
                                       String relativePath)
Apply the given relative path to the given path, assuming standard Java folder separation (i.e. "/" separators);

Parameters:
path - the path to start from (usually a full file path)
relativePath - the relative path to apply (relative to the full file path above)
Returns:
the full file path that results from applying the relative path

cleanPath

public static String cleanPath(String path)
Normalize the path by suppressing sequences like "path/.." and inner simple dots.

The result is convenient for path comparison. For other uses, notice that Windows separators ("\") are replaced by simple slashes.

Parameters:
path - the original path
Returns:
the normalized path Borrowed from Spring, under the ASL2.0 license.

collectionToDelimitedString

public static String collectionToDelimitedString(Collection coll,
                                                 String delim,
                                                 String prefix,
                                                 String suffix)
Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful for toString() implementations.

Parameters:
coll - the Collection to display
delim - the delimiter to use (probably a ",")
prefix - the String to start each element with
suffix - the String to end each element with
Returns:
the delimited String Borrowed from Spring, under the ASL2.0 license.

collectionToDelimitedString

public static String collectionToDelimitedString(Collection coll,
                                                 String delim)
Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful for toString() implementations.

Parameters:
coll - the Collection to display
delim - the delimiter to use (probably a ",")
Returns:
the delimited String Borrowed from Spring, under the ASL2.0 license.

replace

public static String replace(String inString,
                             String oldPattern,
                             String newPattern)
Replace all occurences of a substring within a string with another string.

Parameters:
inString - String to examine
oldPattern - String to replace
newPattern - String to insert
Returns:
a String with the replacements Borrowed from Spring, under the ASL2.0 license.

toURI

public static URI toURI(String location)
                 throws URISyntaxException
Throws:
URISyntaxException

escapeXmlString

public static String escapeXmlString(String string)

delimitedListToStringArray

public static String[] delimitedListToStringArray(String str,
                                                  String delimiter)
Take a String which is a delimited list and convert it to a String array.

A single delimiter can consists of more than one character: It will still be considered as single delimiter string, rather than as bunch of potential delimiter characters - in contrast to tokenizeToStringArray.

Parameters:
str - the input String
delimiter - the delimiter between elements (this is a single delimiter, rather than a bunch individual delimiter characters)
Returns:
an array of the tokens in the list
See Also:
Borrowed from Spring, under the ASL2.0 license.

delimitedListToStringArray

public static String[] delimitedListToStringArray(String str,
                                                  String delimiter,
                                                  String charsToDelete)
Take a String which is a delimited list and convert it to a String array.

A single delimiter can consists of more than one character: It will still be considered as single delimiter string, rather than as bunch of potential delimiter characters - in contrast to tokenizeToStringArray.

Parameters:
str - the input String
delimiter - the delimiter between elements (this is a single delimiter, rather than a bunch individual delimiter characters)
charsToDelete - a set of characters to delete. Useful for deleting unwanted line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
Returns:
an array of the tokens in the list
See Also:
Borrowed from Spring, under the ASL2.0 license.

toStringArray

public static String[] toStringArray(Collection collection)
Copy the given Collection into a String array. The Collection must contain String elements only.

Parameters:
collection - the Collection to copy
Returns:
the String array (null if the passed-in Collection was null) Borrowed from Spring, under the ASL2.0 license.

deleteAny

public static String deleteAny(String inString,
                               String charsToDelete)
Delete any character in a given String.

Parameters:
inString - the original String
charsToDelete - a set of characters to delete. E.g. "az\n" will delete 'a's, 'z's and new lines.
Returns:
the resulting String Borrowed from Spring, under the ASL2.0 license.

toString

public static String toString(Reader reader)
                       throws IOException
Throws:
IOException

toString

public static String toString(InputStream is)
                       throws IOException
Throws:
IOException

toString

public static String toString(BufferedReader reader)
                       throws IOException
Throws:
IOException

generateUUID

public static String generateUUID()

extractFirstIdentifier

public static String extractFirstIdentifier(String string,
                                            int start)

extractFirstIdentifier

public static int extractFirstIdentifier(String string,
                                         StringBuilder builder,
                                         int start)

skipBlanks

public static int skipBlanks(String string,
                             int start)

splitStatements

public static List<String> splitStatements(CharSequence string)

splitArgumentsList

public static List<String> splitArgumentsList(CharSequence string)

findEndMethodArgs

public static int findEndMethodArgs(CharSequence string,
                                    int startMethodArgs)

indexOfOutOfQuotes

public static int indexOfOutOfQuotes(String str,
                                     String searched)

indexOfOutOfQuotes

public static int indexOfOutOfQuotes(String str,
                                     char searched)

isIdentifier

public static boolean isIdentifier(String expr)

stringSimilarity

public static double stringSimilarity(String s1,
                                      String s2,
                                      StringUtils.SIMILARITY_STRATS method)


Copyright © 2001-2014 JBoss by Red Hat. All Rights Reserved.