Class StringUtility
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classA specialized implementation ofArrayList<String>that initializes its elements based on an input array of strings. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedA utility class providing a collection of static methods for performing various operations and manipulations on strings. -
Method Summary
Modifier and TypeMethodDescriptionstatic String[]Append a new element to an array.static StringbitsValue(int value, StringList valueLabels) Converts the bits in the given integer value into a comma-separated string based on the corresponding labels in the provided list.static StringConverts an integer value into a string representation using the provided array of value labels.collect(T list, StringList items) Adds all elements from the specified StringList to the provided list and returns the updated list.Adds the elements from the specified array to the given list.static String[]Concatenate two string arrays.static String[]Get a duplicate string array copy of the array passed.static intdistanceLevenshtein(String s, String t) Find the Levenshtein distance between two strings.static StringencodeForXML(Object obj) Encode and return the string representation of the object passed.static booleanequals(CharSequence one, CharSequence two) See if 2 character sequences contain the same sequence of charactersstatic Stringfill(String source, StringFiller filler) Replace variables in the source string with values returned by the filler.intfindNonWhitespace(String s, int from) Find the next non-whitespace position.intfindWhitespace(String s, int from) Find the next whitespace position.static StringConvert a string to a proper case (the first letter of each word will be capitalized).static String[]Convert each element of the string array to a proper case (the first letter of each word will be capitalized).static Stringformat(double value) Formats a double value as a numeric string.static Stringformat(double value, boolean separated) Formats a double value as a numeric string.static Stringformat(double value, int decimals) Formats a double value as a numeric string with a thousand separation.static Stringformat(double value, int decimals, boolean separated) Formats a double value as a numeric string with a thousand separation.static StringFormats a string as a numeric string with the thousand separations.static StringformatIndian(double value, boolean separated) Formats a double value as a numeric string (Indian style).static StringformatIndian(double value, int decimals, boolean separated) Formats a double value as a numeric string with thousands separation (Indian style).static StringformatIndian(String s, int decimals, boolean separated) Formats a string as a numeric string with a thousand separation (Indian style).static intgetCharCount(String text, char c) Gets the number of occurrences of a given character in the string.static String[]getCSV(BufferedReader reader) Reads a single line of CSV (Comma-Separated Values) data from a BufferedReader and parses it into an array of strings.static intgetStringCount(String text, String pattern) Gets the number of occurrences of a given string in this string.static StringRetrieves the stack trace of the specified thread as a string.static StringRetrieves a string representation of the stack trace for the provided throwable.static intFind the index of an element in an array.static intFind the index of an element in an array.static intFind the index of an element in an array.static String[]Insert a new element at the given index.static booleanCheck if a String contains only space charactersstatic booleanCheck if a String contains only digitsstatic booleanCheck if a String contains only lettersstatic booleanCheck if a String contains only letters and digitsstatic booleanisModulus11(long number) Check the number passed to see if it ends with a modulus 11 check digit.static booleanisModulus11(String alphanumeric) Check the alphanumeric string passed to see if it ends with a modulus 11 check digit.static booleanCheck if a String contains a numeric value or not.static booleanisWhite(char c) Check if the character is a white space or notstatic booleanCheck if a String contains only white space charactersstatic StringMake a label by inserting a space before each capital letter.static StringMake a label by inserting a space before each capital letter.static StringmakeString(int length) Make a String of spaces.static StringmakeString(String s, int length) Make a new String by padding spaces to the String passedstatic StringmakeString(String s, int length, boolean padLeft) Make a new String by padding spaces to the String passedstatic StringmakeString(String s, int length, char padChar, boolean padLeft) Make a new String by padding the padChar to the String passedstatic StringMD5 encryptionstatic StringminutesToAMPM(int time) Converts minutes of the day to human-readable AM/PM string.static StringminutesToString(int duration) Converts time duration to human-readable string "hours:minutes".static intmodulus11(long number) Compute the modulus 11 check digit for the number passed.static intCompute the modulus 11 check digit for the alphanumeric string passed.static StringPack a string by removing white spaces.static String[]Pack all the strings in an array by removing white spaces.static StringLeft pad a String with spacesstatic StringLeft pad a String with the padChar passedstatic StringRight pad a String with spacesstatic StringRight pad a String with the padChar passedstatic PropertiesparseToProperties(String[] args) Parse the string array into "properties".static String[]Remove the first instance of an element from an array.static String[]Remove all instances of an element from an array.static String[]removeNulls(String[] s) Remove null values from the array of Strings.static StringreplaceOutside(String text, CharSequence target, CharSequence replacement) Replaces all occurrences of 'target' with 'replacement' outside the quoted portion (single or double quotes).static StringReplicate a String several timesstatic booleansame(CharSequence one, CharSequence two) Compares two CharSequence objects for equality by checking if they have the same length and identical characters at each corresponding position.static StringSmoothen a string by trimming and replacing double spaces with single space.static StringConverts a string into a 4-character soundex code.static String[]Split the string at the given length into an array.static StringStringify the objectstatic String[]tagDuplicates(String[] s) Tag each element of a String array if it is a duplicate.tagDuplicates(List<String> s) Tag each element of a String list if it is a duplicate.static String[]Convert the list to a String array.static StringtoCamelCase(String text) Convert a string to camelcase.static char[]toCharArray(String[] s) Get a char array from a String array.static StringtoHex(byte[] bytes) Convert a byte array into a String of hex values.static char[]toLowerCase(char[] s) Convert to lower case.static String[]toLowerCase(String[] s) Convert to lower case.static int[]Convert a range string to an int array.static StringtoRangeString(int[] n) Convert an int array into a range string.static StringtoRangeString(Collection<Integer> list) Convert an integer list to a range string.static StringtoString(InputStream stream) Converts the content of the given InputStream into a String.static StringConverts the content of aReaderinto aString.static StringConverts the provided object into its string representation.static char[]toUpperCase(char[] s) Convert to the upper case.static String[]toUpperCase(String[] s) Convert to the upper case.static String[]Trim each element of a String arraystatic StringLeft trim a stringstatic String[]Left trim each element of a String arraystatic StringRight trim a stringstatic String[]Right trim each element of a String arraystatic StringConverts a numeric value into words.static Stringwords(BigDecimal value) Converts a numeric value into words.static Stringwords(BigInteger value) Converts a numeric value into words.static StringwordsIndian(BigDecimal value) Converts a numeric value into words in Indian format.static StringwordsIndian(BigInteger value) Converts a numeric value into words in Indian format.
-
Constructor Details
-
StringUtility
protected StringUtility()A utility class providing a collection of static methods for performing various operations and manipulations on strings. This constructor is protected to prevent direct instantiation of the utility class, ensuring that it is used in a static context only.
-
-
Method Details
-
toCamelCase
-
toLowerCase
-
toUpperCase
-
toLowerCase
public static char[] toLowerCase(char[] s) Convert to lower case.- Parameters:
s- Char array to be converted.- Returns:
- Array
-
toUpperCase
public static char[] toUpperCase(char[] s) Convert to the upper case.- Parameters:
s- Char array to be converted.- Returns:
- Array
-
tagDuplicates
Tag each element of a String array if it is a duplicate. For example, if the array is { "Name", "ShortName", "Name", "Test", "Name" }, it will become { "Name", "ShortName", "Name (2)", "Test", "Name (3)" }. Null values will be untouched.- Parameters:
s- String array to be tagged- Returns:
- Array
-
tagDuplicates
Tag each element of a String list if it is a duplicate. For example, if the list is [ "Name", "ShortName", "Name", "Test", "Name" ], it will become [ "Name", "ShortName", "Name (2)", "Test", "Name (3)" ]. Null values will be untouched.- Parameters:
s- String list to be tagged- Returns:
- Array
-
toArray
-
trim
-
trimRight
-
trimLeft
-
trimRight
-
trimLeft
-
replicate
-
padRight
Right pad a String with spaces- Parameters:
s- String to be padded. A null String is treated as "".length- Length of the String after padding. Warning: The resulting String may be shorter than the passed, one depending on this parameter.- Returns:
- The result String
-
padRight
Right pad a String with the padChar passed- Parameters:
s- String to be padded. A null String is treated as "".length- Length of the String after padding. Warning: The resulting String may be shorter than the passed, one depending on this parameter.padChar- The character to be used for padding.- Returns:
- The result String
-
padLeft
Left pad a String with spaces- Parameters:
s- String to be padded. A null String is treated as "".length- Length of the String after padding. Warning: The resulting String may be shorter than the passed, one depending on this parameter.- Returns:
- The result String
-
padLeft
Left pad a String with the padChar passed- Parameters:
s- String to be padded. A null String is treated as "".length- Length of the String after padding. Warning: The resulting String may be shorter than the passed, one depending on this parameter.padChar- The character to be used for padding.- Returns:
- The result String
-
makeString
Make a String of spaces.- Parameters:
length- The length of the resulting String- Returns:
- The result String
-
makeString
Make a new String by padding spaces to the String passed- Parameters:
s- Input stringlength- Length of the String after padding. Warning: The resulting String may be shorter than the passed one, depending on this parameter.- Returns:
- The result String
-
makeString
Make a new String by padding spaces to the String passed- Parameters:
s- Input stringlength- Length of the String after padding. Warning: The resulting String may be shorter than the passed one, depending on this parameter.padLeft- If passed "true", left padding will happen, otherwise padding will happen on the right- Returns:
- The result String
-
makeString
Make a new String by padding the padChar to the String passed- Parameters:
s- Input stringlength- Length of the String after padding. Warning: The resulting String may be shorter than the passed one, depending on this parameter.padChar- The character to be used for padding.padLeft- If passed "true", left padding will happen, otherwise padding will happen on the right- Returns:
- The result String
-
smoothen
-
pack
-
pack
-
removeNulls
-
toHex
Convert a byte array into a String of hex values. Each is converted to 2 hex characters. For example, StringUtility.toHex(new byte[ ] { 10, 17, 19, 4, 11 }) will return "0A1113040B".- Parameters:
bytes- The byte array to be converted.- Returns:
- The result String
-
isBlank
Check if a String contains only space characters- Parameters:
s- String to be checked- Returns:
- True if the String contains only spaces, otherwise false.
-
isWhite
Check if a String contains only white space characters- Parameters:
s- String to be checked- Returns:
- True if the String contains only white spaces, otherwise false.
-
isWhite
public static boolean isWhite(char c) Check if the character is a white space or not- Parameters:
c- Character to be checked.- Returns:
- True if the character is a white space, otherwise false.
-
isLetterOrDigit
Check if a String contains only letters and digits- Parameters:
s- String to be checked- Returns:
- True if the String contains only letters and digits, otherwise false.
-
isLetter
Check if a String contains only letters- Parameters:
s- String to be checked- Returns:
- True if the String contains only letters, otherwise false.
-
isDigit
Check if a String contains only digits- Parameters:
s- String to be checked- Returns:
- True if the String contains only digits, otherwise false.
-
isNumber
Check if a String contains a numeric value or not.- Parameters:
s- String to be checked- Returns:
- True if the String contains a proper numeric value. (Can contain an optional minus '-' sign and a decimal point).
-
firstCaps
-
firstCaps
-
findWhitespace
Find the next whitespace position.- Parameters:
s- String to be searched.from- The position from which the search should start.- Returns:
- The next whitespace position or the string length if nothing found.
-
findNonWhitespace
Find the next non-whitespace position.- Parameters:
s- String to be searched.from- The position from which the search should start.- Returns:
- The next non-whitespace position or the string length if nothing found.
-
minutesToString
Converts time duration to human-readable string "hours:minutes".- Parameters:
duration- Time duration to convert in minutes.- Returns:
- Human-readable string. Example: 63 will be converted to "01:03".
-
minutesToAMPM
Converts minutes of the day to human-readable AM/PM string.- Parameters:
time- Time to convert in minutes (will be converted to the range 0 <= minutes < 1448).- Returns:
- Human-readable string. Example: 63 will be converted to "01:03 AM".
-
makeLabel
Make a label by inserting a space before each capital letter. Also, all dash characters ("-", "_") are converted into " - ". Single quotes will be copied as such. If "as" keyword is found, the word sequences after that keyword will be used for generating the label.
Examples: "ShortName" => "Short Name", "CountryName" => "Country Name", "CountryOfDestination as Shipment Country" => "Shipment Country", "KGB" => "KGB", "KGBAgent" => "KGB Agent", "eDocument" => "eDocument", "eGovernanceInitiative" => "eGovernance Initiative", "Document_PartI" => "Document - Part I.
Also,
(1) class casting type constructs will be removed. Example: "(com.storedobject.core.Person)Employee" => "Employee"
(2) "A.B.C." => "A.B.C.", "Animal.Lion" => "Lion" (because the letter just before ".Lion" is in small-case).
- Parameters:
s- String to be converted.lowerPropositions- Whether to convert propositions to lower case or not.- Returns:
- Converted string.
-
makeLabel
Make a label by inserting a space before each capital letter. Also, all dash characters ("-", "_") are converted into " - ". Single quotes will be copied as such. If "as" keyword is found, the word sequences after that keyword will be used for generating the label.
Examples: "ShortName" => "Short Name", "CountryName" => "Country Name", "CountryOfDestination as Shipment Country" => "Shipment Country", "KGB" => "KGB", "KGBAgent" => "KGB Agent", "eDocument" => "eDocument", "eGovernanceInitiative" => "eGovernance Initiative", "Document_PartI" => "Document - Part I.
Also,
(1) class casting type constructs will be removed. Example: "(com.storedobject.core.Person)Employee" => "Employee"
(2) "A.B.C." => "A.B.C.", "Animal.Lion" => "Lion" (because the letter just before ".Lion" is in small-case).
- Parameters:
s- String to be converted.- Returns:
- Converted string.
-
toRangeString
Convert an integer list to a range string. For example, { 1, 2, 3, 5, 7, 8, 9 } will be converted to "1 - 3, 5, 7 - 9".- Parameters:
list- List of numbers to be converted.- Returns:
- Range string
-
toRangeString
Convert an int array into a range string. For example, an array { 1, 2, 3, 5, 7, 8, 9 } will be converted to "1 - 3, 5, 7 - 9".- Parameters:
n- int array of numbers to be converted.- Returns:
- Range string
-
toNumericRange
Convert a range string to an int array. For example, "1 - 3, 5, 7 - 9" will be converted to an array { 1, 2, 3, 5, 7, 8, 9 }.- Parameters:
s- String to be converted.- Returns:
- int array containing the numbers. Null will be returned if the parameter passed contains errors.
-
soundex
-
getCharCount
Gets the number of occurrences of a given character in the string.- Parameters:
text- String to be scanned.c- Character to look for.- Returns:
- Occurrences
-
getStringCount
-
replaceOutside
Replaces all occurrences of 'target' with 'replacement' outside the quoted portion (single or double quotes).- Parameters:
text- String to operate on.target- Target sequence to replacereplacement- Replacement text- Returns:
- Replaced string
-
encodeForXML
Encode and return the string representation of the object passed. This encoding is useful for creating strings that can be used in XML texts. That is, it replaces characters such as "<", "&", ">" etc. the respective encoded values "<", "&", ">" etc.- Parameters:
obj- The object to convert.- Returns:
- XML encoded string.
-
modulus11
public static int modulus11(long number) Compute the modulus 11 check digit for the number passed.- Parameters:
number- Number- Returns:
- Check a digit. -1 is returned for invalid numbers.
-
modulus11
Compute the modulus 11 check digit for the alphanumeric string passed.- Parameters:
alphanumeric- Input- Returns:
- Check a digit. -1 is returned for invalid numbers and -2 is returned for invalid strings.
-
isModulus11
Check the alphanumeric string passed to see if it ends with a modulus 11 check digit.- Parameters:
alphanumeric- Input- Returns:
- True or false.
-
isModulus11
public static boolean isModulus11(long number) Check the number passed to see if it ends with a modulus 11 check digit.- Parameters:
number- Number- Returns:
- True or false.
-
stringify
-
copy
Get a duplicate string array copy of the array passed. Each element from the source array will be stringified.- Parameters:
objects- Array of any object copy.- Returns:
- Copy of the array as a string array. If the input is null, the output will also be null. Null elements in the source array will generate a null element in the output array.
-
toCharArray
Get a char array from a String array.- Parameters:
s- Array to be converted.- Returns:
- character array created by taking the first characters of the String array. For null values and values of length zeros, a space is set for the corresponding character values.
-
insert
-
append
-
remove
-
removeAll
-
concat
-
indexOf
-
indexOf
-
indexOf
Find the index of an element in an array.- Parameters:
a- Array.element- Element to be searched.from- From indexto- To index- Returns:
- First index of the element. -1 is returned if the array is null or the element is not found.
-
split
Split the string at the given length into an array. New line characters will be treated as if splitting is needed at that position. An attempt is made to split at word boundaries if possible. "\r" (carriage return) characters will be removed.- Parameters:
s- String to split.length- Length at which the split happens.- Returns:
- Array of strings containing each part of the string.
-
parseToProperties
Parse the string array into "properties". This is useful to parse "command line" parameters.- Parameters:
args- Argument list as a string array.- Returns:
- Properties containing all the argument values passed as the array.
- Throws:
SOException- if anything in the argument does not look like a "command line" parameter.
-
distanceLevenshtein
-
bitsValue
Converts an integer value into a string representation using the provided array of value labels. Each bit in the integer value is matched with a corresponding label in the array.- Parameters:
value- The integer value whose bits are to be interpreted.valueLabels- An array of strings representing the labels for each bit position.- Returns:
- A string that represents the bit values mapped to the corresponding labels.
-
bitsValue
Converts the bits in the given integer value into a comma-separated string based on the corresponding labels in the provided list.- Parameters:
value- the integer whose bits are to be processedvalueLabels- the list of labels corresponding to the bit positions- Returns:
- a comma-separated string representing the labels for the set bits in the integer value, in order of the bit positions
-
same
Compares two CharSequence objects for equality by checking if they have the same length and identical characters at each corresponding position.- Parameters:
one- the first CharSequence to comparetwo- the second CharSequence to compare- Returns:
- true if the two CharSequences are of the same length and have the same characters at each position, false otherwise
-
format
Formats a double value as a numeric string. Up to 14 fractional digits will be considered. If you want the thousand separations, please useformat(double, boolean).- Parameters:
value- Double value to be converted.- Returns:
- Formatted value
-
format
Formats a double value as a numeric string. Up to 14 fractional digits will be considered.- Parameters:
value- Double value to be converted.separated- True if thousands of separations are needed in the output.- Returns:
- Formatted value
-
formatIndian
Formats a double value as a numeric string (Indian style). Up to 14 fractional digits will be considered.- Parameters:
value- Double value to be converted.separated- True if thousands of separations are needed in the output.- Returns:
- Formatted value
-
format
Formats a double value as a numeric string with a thousand separation.- Parameters:
value- Double value to be converted.decimals- Number of decimals required in the output string. Passing -1 causes all non-zero decimals up to 14 positions to be incorporated.- Returns:
- Formatted value
-
format
Formats a double value as a numeric string with a thousand separation.- Parameters:
value- Double value to be converted.decimals- Number of decimals required in the output string. Passing -1 causes all non-zero decimals up to 14 positions to be incorporated.separated- True if a thousand separation are needed in the output.- Returns:
- Formatted value
-
formatIndian
Formats a double value as a numeric string with thousands separation (Indian style).- Parameters:
value- Double value to be converted.decimals- Number of decimals required in the output string. Passing -1 causes all non-zero decimals up to 14 positions to be incorporated.separated- True if a thousand separation is needed in the output.- Returns:
- Formatted value
-
format
Formats a string as a numeric string with the thousand separations.- Parameters:
s- String of digits (can contain a decimal point).decimals- Number of decimals required in the output string.separated- True if a thousand separation is needed in the output.- Returns:
- Formatted value
-
formatIndian
Formats a string as a numeric string with a thousand separation (Indian style).- Parameters:
s- String of digits (can contain a decimal point).decimals- Number of decimals required in the output string.separated- True if a thousand separation is needed in the output.- Returns:
- Formatted value
-
words
-
words
Converts a numeric value into words. Decimal portion and negative part will be ignored- Parameters:
value- Value- Returns:
- Value in words
-
words
Converts a numeric value into words. Negative part will be ignored- Parameters:
value- Value- Returns:
- Value in words
-
wordsIndian
Converts a numeric value into words in Indian format. Decimal portion and negative part will be ignored- Parameters:
value- Value- Returns:
- Value in words in Indian format
-
wordsIndian
Converts a numeric value into words in Indian format. Decimal portion and negative part will be ignored- Parameters:
value- Value- Returns:
- Value in words in Indian format
-
equals
See if 2 character sequences contain the same sequence of characters- Parameters:
one- First character sequence.two- Second character sequence.- Returns:
- True/False.
-
getTrace
-
getTrace
-
toString
Converts the provided object into its string representation. If the object implements the Displayable interface, its `toDisplay` method will be used to generate the string. Otherwise, a default string conversion is applied.- Parameters:
message- the object to be converted into a string representation- Returns:
- the string representation of the provided object
-
toString
Converts the content of the given InputStream into a String.- Parameters:
stream- the InputStream to be converted; may be null.- Returns:
- a String representation of the content of the InputStream, or null if the provided InputStream is null.
- Throws:
Exception- if an error occurs while reading the InputStream.
-
toString
Converts the content of aReaderinto aString.- Parameters:
reader- theReadercontaining the input to be converted; ifnull, the method will returnnull.- Returns:
- a
Stringrepresentation of the content read from the providedReader, ornullif the inputReaderisnull. - Throws:
Exception- if there is an error while reading from theReader.
-
getCSV
Reads a single line of CSV (Comma-Separated Values) data from a BufferedReader and parses it into an array of strings. Handles multi-line fields enclosed in quotes and line continuations where necessary.- Parameters:
reader- The BufferedReader to read input from. Must not be null.- Returns:
- An array of strings containing the parsed CSV fields, or null if the input line is empty or null.
- Throws:
Exception- If an error occurs during parsing or if a multi-line field is improperly terminated.
-
fill
Replace variables in the source string with values returned by the filler. Variables in the source string are of the form ${VariableName}. A sample source may look like "My name is ${name} and my age is ${age}". Here, 'name' and 'age' are the variables, and the values returned by filler.fill("name") and filler.fill("age") will be used to replace the variables in the string. So, the resulting string will look like "My name is Syam Pillai and my age is 40" if the return values are "Syam Pillai" and "40" respectively.- Parameters:
source- The source string.filler- The filler logic.- Returns:
- Result of substituting the variables in the source string with respective values returned by the filler logic.
-
collect
Adds the elements from the specified array to the given list.- Type Parameters:
T- the type of the list- Parameters:
list- the list to which elements should be added; must extend List of Stringsitems- the array of strings to be added to the list- Returns:
- the modified list containing the original elements and the new elements from the array
-
collect
Adds all elements from the specified StringList to the provided list and returns the updated list.- Type Parameters:
T- the type of the list- Parameters:
list- the list to which elements will be addeditems- the StringList containing elements to add to the list- Returns:
- the updated list containing the added elements
-
md5
-