TUM CCSM Commons

edu.tum.cs.commons.string
Class StringUtils

java.lang.Object
  extended by edu.tum.cs.commons.string.StringUtils

public class StringUtils
extends Object

A utility class providing some advanced string functionality.

Version:
$Rev: 29159 $
Author:
Daniel Ratiu, Florian Deissenboeck, Tilman Seifert, $Author: heineman $
Rating:
GREEN Hash: 3C85A252901D3932299CFD62BF0FA9B0

Field Summary
static String CR
          Line break.
static String EMPTY_STRING
          The emtpy string.
static String LINE_TERMINATOR_SYMBOL
          A symbol representing the line terminator.
static String SPACE
          A space.
static char SPACE_CHAR
          A space character.
static String TAB
          A tab character.
static String TWO_SPACES
          Two spaces.
 
Constructor Summary
StringUtils()
           
 
Method Summary
static String addRandomLineBreaks(String text, int count)
          Adds random line breaks to a string.
static String bytesToString(byte[] b)
          Converts a (UTF-8) byte array to a string.
static String camelCaseToHyphenated(String s)
          Transforms a string from camel-case to lower-case with hyphens.
static String capitalize(String string)
          Capitalize string.
static String center(String string, int length, char c)
          Create a sting of the given length and center the given string within it.
static String concat(Iterable<?> iterable)
          Concatenates all elements of an iterable using the toString()-method.
static String concat(Iterable<?> iterable, String separator)
          Concatenates all elements of an iterable using the toString()-method, separating them with the given separator.
static String concat(Object[] array)
          Concatenates all elements of an array using the toString() -method.
static String concat(Object[] array, String separator)
          Concatenates all elements of an array using the toString() -method, separating them with the given separator.
static String[] concat(String[] array1, String[] array2)
          Concatenate two string arrays.
static boolean containsOneOf(String text, String... strings)
          Test if a string contains of the provided strings.
static String createUniqueName(String baseName, Set<String> usedNames)
          Creates a unique name which is not contained in the given set of names.
static byte[] decodeFromHex(String s)
          Decodes a byte array from a hex string.
static String encodeAsHex(byte[] data)
          Encodes a byte array as a hex string.
static boolean endsWithOneOf(String string, String... suffixes)
          Test if a string ends with one of the provided suffixes.
static String escapeRegexReplacementString(String replacement)
          Regex replacement methods like Matcher.appendReplacement(StringBuffer, String) or String.replaceAll(String, String) treat dollar signs as group references.
static String fillString(int length, char c)
          Build a string with a specified length from a character.
static String flushLeft(String string, int length, char c)
          Create a sting of the given length starting with the provided string.
static String flushRight(String string, int length, char c)
          Create a sting of the given length ending with the provided string.
static String format(double number, NumberFormat numberFormat)
          Format number with number formatter, if number formatter is null, this uses String.valueOf(double).
static String format(Number number)
          Format number
static String formatAsPercentage(Number number)
          Format as percentage.
static String generateString(int length, int seed)
          Generates a pseudo random string with a certain length in a deterministic, reproducable fashion.
static String[] generateStringArray(int length, int stringLength, int seed)
          Generates an array of pseudo-random strings in a deterministic, reproducable fashion.
static String getFirstLine(String string)
          Returns the first line of a string.
static String getFirstParts(String string, int partNumber, char separator)
          Returns the first n part of a string, separated by the given character.
static HashMap<String,String> getKeyValuePairs(String keyValueString)
          Splits a key-value string and stores it in a hash map.
static String getLastPart(String string, char separator)
          Return the last part of a String which is separated by the given character.
static int indexOf(String[] array, String string)
          Searches the elements of a string array for a string.
static boolean isEmpty(String text)
          Checks if a string is empty (after trimming).
static String longestCommonPrefix(Iterable<String> strings)
          Returns the longest common prefix of the strings in the list or the empty string if no common prefix exists.
static String longestCommonPrefix(String s, String t)
          Returns the longest common prefix of s and t
static String normalizeLineBreaks(String string)
          Replace all linebreaks in string with the platform-specific line separator.
static String obtainStackTrace(Throwable throwable)
          Convert stack trace of a Throwable to a string.
static String prefixLines(String string, String prefix, boolean prefixFirstLine)
          Prefix all lines of a string.
static String randomString(int length)
          Generates a random string with a certain length.
static String[] randomStringArray(int length, int stringLength)
          Generates an array of random strings.
static String removeLastPart(String string, char separator)
          Returns the beginning of a String, cutting off the last part which is separated by the given character.
static String removeWhitespace(String content)
          Removes whitespace from a string.
static String replaceLineBreaks(String string)
          Replace all linebreaks in string with LINE_TERMINATOR_SYMBOL.
static String replaceLineBreaks(String string, String symbol)
          Replace all linebreaks in string by a specified symbol.
static Character[] splitChars(String s)
          Splits the given string into an array of Characters.
static String[] splitLines(String content)
          Split string in lines.
static List<String> splitLinesAsList(String content)
          Split string in lines.
static boolean startsWithOneOf(String string, String... prefixes)
          Test if a string starts with one of the provided prefixes.
static byte[] stringToBytes(String s)
          Converts a string to a (UTF-8) byte representation.
static String stripDigits(String string)
          Strips all digits from the given String.
static String stripPrefix(String prefix, String string)
          Remove prefix from a string.
static String stripSuffix(String suffix, String string)
          Remove suffix from a string.
static String toString(Map<?,?> map)
          Create string representation of a map.
static String toString(Map<?,?> map, String indent)
          Create string representation of a map.
static String wrapLongLines(String s, int maxLineLength)
          This method splits the input string into words (delimited by whitespace) and returns a string whose words are separated by single spaces and whose lines are not longer than the given length (unless a very long word occurs)).
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CR

public static final String CR
Line break.


EMPTY_STRING

public static final String EMPTY_STRING
The emtpy string.

See Also:
Constant Field Values

LINE_TERMINATOR_SYMBOL

public static final String LINE_TERMINATOR_SYMBOL
A symbol representing the line terminator.

See Also:
Constant Field Values

SPACE

public static final String SPACE
A space.

See Also:
Constant Field Values

SPACE_CHAR

public static final char SPACE_CHAR
A space character.

See Also:
Constant Field Values

TAB

public static final String TAB
A tab character.

See Also:
Constant Field Values

TWO_SPACES

public static final String TWO_SPACES
Two spaces.

See Also:
Constant Field Values
Constructor Detail

StringUtils

public StringUtils()
Method Detail

addRandomLineBreaks

public static String addRandomLineBreaks(String text,
                                         int count)
Adds random line breaks to a string.

Parameters:
text - the original string.
count - the number of line breaks to add.
Returns:
the string with line breaks.

center

public static String center(String string,
                            int length,
                            char c)
Create a sting of the given length and center the given string within it. Left and right areas are filled by the character provided.

Parameters:
string - The input string.
length - The length of the string to be returned.
c - The character to surround the input string with.
Returns:
the new string or, if the string is longer than the specified length, the original string.
See Also:
flushLeft(String, int, char), flushRight(String, int, char)

concat

public static String concat(Iterable<?> iterable)
Concatenates all elements of an iterable using the toString()-method.

Parameters:
iterable - the iterable
Returns:
a concatenation, separated by spaces

concat

public static String concat(Iterable<?> iterable,
                            String separator)
Concatenates all elements of an iterable using the toString()-method, separating them with the given separator.

Parameters:
iterable - the iterable containing the strings
separator - the separator to place between the strings, may be null
Returns:
a concatenation of the string in the array or null if array was null. If array is of length 0 the empty string is returned.

concat

public static String concat(Object[] array)
Concatenates all elements of an array using the toString() -method.

Parameters:
array - the array containing the strings
Returns:
a concatenation of the string separated by spaces

concat

public static String concat(Object[] array,
                            String separator)
Concatenates all elements of an array using the toString() -method, separating them with the given separator.

Parameters:
array - the array
separator - the separator to place between the strings, may be null
Returns:
a concatenation of the string in the array or null if array was null. If array is of length 0 the empty string is returned.

concat

public static String[] concat(String[] array1,
                              String[] array2)
Concatenate two string arrays.

Parameters:
array1 -
array2 -
Returns:
the concatenation

fillString

public static String fillString(int length,
                                char c)
Build a string with a specified length from a character.

Parameters:
length - The length of the string.
c - The character.
Returns:
The string.

flushLeft

public static String flushLeft(String string,
                               int length,
                               char c)
Create a sting of the given length starting with the provided string. Remaining characters are filled with the provided character.

Parameters:
string - The input string.
length - The length of the string to be returned.
c - The character to fill the string.
Returns:
the new string or, if the string is longer than the specified length, the original string.
See Also:
flushRight(String, int, char), center(String, int, char)

flushRight

public static String flushRight(String string,
                                int length,
                                char c)
Create a sting of the given length ending with the provided string. Remaining characters are filled with the provided character.

Parameters:
string - The input string.
length - The length of the string to be returned.
c - The character to fill the string.
Returns:
the new string or, if the string is longer than the specified length, the original string.
See Also:
flushLeft(String, int, char), center(String, int, char)

format

public static String format(Number number)
Format number


formatAsPercentage

public static String formatAsPercentage(Number number)
Format as percentage.


getFirstLine

public static String getFirstLine(String string)
Returns the first line of a string.


getFirstParts

public static String getFirstParts(String string,
                                   int partNumber,
                                   char separator)
Returns the first n part of a string, separated by the given character. E.g., getStringParts("edu.tum.cs", 2, '.') gives: "edu.tum".

Parameters:
string - the base string
partNumber - number of parts
separator - the separator character

getKeyValuePairs

public static HashMap<String,String> getKeyValuePairs(String keyValueString)
Splits a key-value string and stores it in a hash map. The string must have the following format:

key=value[,key=value]*

If the string is null null is returned.

Parameters:
keyValueString - with format described above
Returns:
a hash map containing the key-values-pairs.

getLastPart

public static String getLastPart(String string,
                                 char separator)
Return the last part of a String which is separated by the given character. E.g., getLastPart("edu.tum.cs.commons.string.StringUtils", '.') gives "StringUtils".

Parameters:
string - the String
separator - separation character
Returns:
the last part of the String, or the original String if the separation character is not found.

indexOf

public static int indexOf(String[] array,
                          String string)
Searches the elements of a string array for a string. Strings are trimmed.

Parameters:
array - the array to search
string - the search string
Returns:
the index of the element where the string was found or -1 if string wasn't found.

isEmpty

public static boolean isEmpty(String text)
Checks if a string is empty (after trimming).

Parameters:
text - the string to check.
Returns:
true if string is empty or null, false otherwise.

randomString

public static String randomString(int length)
Generates a random string with a certain length. The string consists of characters with ASCII code between 33 and 126.

Parameters:
length - the length of the random string
Returns:
the random string

randomStringArray

public static String[] randomStringArray(int length,
                                         int stringLength)
Generates an array of random strings.

Parameters:
length - number of strings
stringLength - length of each string
Returns:
the randomly generated array.

generateString

public static String generateString(int length,
                                    int seed)
Generates a pseudo random string with a certain length in a deterministic, reproducable fashion.

Parameters:
length - the length of the pseudo-random string
seed - seed value for the random number generator used for the generation of the pseudo-random string. If the same seed value is used, the same pseudo-random string is generated.

generateStringArray

public static String[] generateStringArray(int length,
                                           int stringLength,
                                           int seed)
Generates an array of pseudo-random strings in a deterministic, reproducable fashion.

Parameters:
length - number of strings
stringLength - length of each string
seed - seed value for the random number generator used for the generation of the pseudo-random string. If the same seed value is used, the same pseudo-random string array is generated.
Returns:
the randomly generated array.

removeLastPart

public static String removeLastPart(String string,
                                    char separator)
Returns the beginning of a String, cutting off the last part which is separated by the given character. E.g., removeLastPart("edu.tum.cs.commons.string.StringUtils", '.') gives "edu.tum.cs.commons.string".

Parameters:
string - the String
separator - separation character
Returns:
the String without the last part, or the original string if the separation character is not found.

replaceLineBreaks

public static String replaceLineBreaks(String string)
Replace all linebreaks in string with LINE_TERMINATOR_SYMBOL.

Returns:
a string without linebreaks

normalizeLineBreaks

public static String normalizeLineBreaks(String string)
Replace all linebreaks in string with the platform-specific line separator.

Returns:
a string without linebreaks

replaceLineBreaks

public static String replaceLineBreaks(String string,
                                       String symbol)
Replace all linebreaks in string by a specified symbol.

Returns:
a string with line breaks replaced.

splitLines

public static String[] splitLines(String content)
Split string in lines. For the the empty string and null an array of length zero is returned.

See Also:
splitLinesAsList(String)

splitLinesAsList

public static List<String> splitLinesAsList(String content)
Split string in lines. For the the empty string and null an empty list is returned.

See Also:
splitLines(String)

stripPrefix

public static String stripPrefix(String prefix,
                                 String string)
Remove prefix from a string.

Parameters:
prefix - the prefix
string - the string
Returns:
the string without the prefix or the original string if it does not start with the prefix.

stripSuffix

public static String stripSuffix(String suffix,
                                 String string)
Remove suffix from a string.

Parameters:
suffix - the suffix
string - the string
Returns:
the string without the suffix or the original string if it does not end with the suffix.

stripDigits

public static String stripDigits(String string)
Strips all digits from the given String.


toString

public static String toString(Map<?,?> map)
Create string representation of a map.


toString

public static String toString(Map<?,?> map,
                              String indent)
Create string representation of a map.

Parameters:
map - the map
indent - a line indent

obtainStackTrace

public static String obtainStackTrace(Throwable throwable)
Convert stack trace of a Throwable to a string.


startsWithOneOf

public static boolean startsWithOneOf(String string,
                                      String... prefixes)
Test if a string starts with one of the provided prefixes. Returns false if the list of prefixes is empty. This should only be used for short lists of prefixes.


containsOneOf

public static boolean containsOneOf(String text,
                                    String... strings)
Test if a string contains of the provided strings. Returns false if the list of strings is empty. This should only be used for short lists of strings.


endsWithOneOf

public static boolean endsWithOneOf(String string,
                                    String... suffixes)
Test if a string ends with one of the provided suffixes. Returns false if the list of prefixes is empty. This should only be used for short lists of suffixes.


prefixLines

public static String prefixLines(String string,
                                 String prefix,
                                 boolean prefixFirstLine)
Prefix all lines of a string. This also replaces line breaks with the platform-specific line-separator.

Parameters:
string - the string to prefix
prefix - the prefix to add
prefixFirstLine - a flag that indicates if the first line should be prefixed or not.

splitChars

public static Character[] splitChars(String s)
Splits the given string into an array of Characters. This is mostly used for testing purposes, if an array of certain objects is needed.


capitalize

public static String capitalize(String string)
Capitalize string.


wrapLongLines

public static String wrapLongLines(String s,
                                   int maxLineLength)
This method splits the input string into words (delimited by whitespace) and returns a string whose words are separated by single spaces and whose lines are not longer than the given length (unless a very long word occurs)).


longestCommonPrefix

public static String longestCommonPrefix(String s,
                                         String t)
Returns the longest common prefix of s and t


longestCommonPrefix

public static String longestCommonPrefix(Iterable<String> strings)
Returns the longest common prefix of the strings in the list or the empty string if no common prefix exists.


removeWhitespace

public static String removeWhitespace(String content)
Removes whitespace from a string.


createUniqueName

public static String createUniqueName(String baseName,
                                      Set<String> usedNames)
Creates a unique name which is not contained in the given set of names. If possible the given base name is directly returned, otherwise it is extended by a number.


camelCaseToHyphenated

public static String camelCaseToHyphenated(String s)
Transforms a string from camel-case to lower-case with hyphens.


encodeAsHex

public static String encodeAsHex(byte[] data)
Encodes a byte array as a hex string.


decodeFromHex

public static byte[] decodeFromHex(String s)
Decodes a byte array from a hex string.


format

public static String format(double number,
                            NumberFormat numberFormat)
Format number with number formatter, if number formatter is null, this uses String.valueOf(double).


escapeRegexReplacementString

public static String escapeRegexReplacementString(String replacement)
Regex replacement methods like Matcher.appendReplacement(StringBuffer, String) or String.replaceAll(String, String) treat dollar signs as group references. This method escapes replacement strings so that dollar signs are treated as literals.


stringToBytes

public static byte[] stringToBytes(String s)
Converts a string to a (UTF-8) byte representation.


bytesToString

public static String bytesToString(byte[] b)
Converts a (UTF-8) byte array to a string.


TUM CCSM Commons

TUM CCSM Commons - 2.7