|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objectnl.knowledgeplaza.util.StringUtil
public class StringUtil
This class contains several String helper methods.
| Field Summary | |
|---|---|
static String |
FILTERCHARS_BACKSLASH
|
static String |
FILTERCHARS_DIGITS
|
static String |
FILTERCHARS_LOWERLETTERS
|
static String |
FILTERCHARS_PUNCTUATION
|
static String |
FILTERCHARS_QUOTES
|
static String |
FILTERCHARS_UPPERLETTERS
|
static String |
SOURCECODE_VERSION
Standard variable for determining version of a class file. |
| Constructor Summary | |
|---|---|
StringUtil()
|
|
| Method Summary | |
|---|---|
static String |
byteArrayToString(byte[] ba)
Returns a byte array as a java string |
static String |
byteArrayToString(byte[] ba,
int offset,
int len)
Returns a byte array as a java string |
static String |
byteToHex(byte b)
Returns hex String representation of byte b |
static String |
byteToHex(byte[] b)
Returns hex String representation of bytes b |
static String |
charToHex(char c)
Returns hex String representation of char c |
static boolean |
contains(String str,
char chr)
Return true if the string contains the other character. |
static boolean |
contains(String str,
String sub)
Return true if the string contains the other string. |
static String |
convertStandardTypesToString(Object o)
|
static Object |
convertStringToStandardTypes(String s,
Class c)
|
static int |
count(String text,
String pattern)
counts how many times the given pattern occurs in the given text. |
static int |
countWords(String s,
String delimiter)
|
static String |
deleteChars(String str,
String chars)
Delete all occurencies of certain characters in a string. |
static boolean |
equalsTrueInSomeForm(String s)
all of "true", "yes" or "1", case insensitive and trimmed, are considered 'true' |
static boolean |
equalsTrueInSomeForm(String s,
boolean nullOrEmptyValue)
all of "true", "yes" or "1", case insensitive and trimmed, are considered 'true' |
static String |
escapeForSQL(String in)
Helper function for escaping strings that should be used in SQL queries. |
static String |
escapeHTML(String s)
Replaces characters that may be confused by a HTML parser with their equivalent character entity references. |
static String |
escapeHTMLTag(String aTagFragment)
Replace characters having special meaning inside HTML tags with their escaped equivalents, using character entities such as '&'. |
static String |
escapeJavaLiteral(String s)
Replaces characters that are not allowed in a Java style string literal with their escape characters. |
static String |
escapeRegex(String aRegexFragment)
Replace characters having special meaning in regular expressions with their escaped equivalents. |
static String |
escapeSQL(String s)
Replaces characters that may be confused by an SQL parser with their equivalent escape characters. |
static String |
escapeString(String in)
Escape all String delimiter with \ |
static String |
escapeURL(String aURLFragment)
Synonym for URLEncoder.encode(String, "UTF-8"). |
static String |
escapeXML(String text)
Escape characters for text appearing as XML data, between tags. |
static String |
filter(String original,
String filter)
Only allow those characters that are present in the filter filter("aAAcA-1%23", "ABCDEFGHIJKLMNOPQRSTIUVWXYZ1234567890") returns AAA123 |
static String |
filterChars(String from,
String chars)
Leave any of the characters in chars in the string |
static String |
firstCharacterLowercase(String s)
Make the first character lowercase |
static String |
firstCharacterUppercase(String s)
Make the first character uppercase |
static String |
firstWord(String s)
|
static String |
flattenString(String in)
throw away all line feeds |
static String |
fromJavaStringLiteral(String str)
Convert a backslash notation into a String (e.g. backslash-n as newline). |
static String |
ifEmpty(String s,
String d)
if s is null or length=0 return d else s |
static String |
ifNull(String s,
String d)
if s is null return d else s |
static String |
insertAt(String s,
int startIdx,
String s2)
insert a piece into a string |
static boolean |
isDecimal(String s)
Check if a string contains an decimal TODO improve implementation: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java |
static boolean |
isEmpty(String s)
true if s is null or length=0 |
static boolean |
isEmptyWhitespace(String s)
true if s == null or trimmed length=0 |
static boolean |
isInteger(String s)
Check if a string contains an integer TODO improve implementation: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java |
static boolean |
isMatch(String pattern,
String string)
This method does a wildcard match (using * and ?) |
static boolean |
isNotEmpty(String s)
true if s ! |
static boolean |
isNotEmptyWhitespace(String s)
true if s ! |
static String |
left(String aString,
int len)
equivalent to the basic "left" function |
static String |
makeCSV(String separator,
String... values)
Generate a new string where each (empty or not) value is separated by the separator. |
static String |
makeCSVOfNonEmpty(String separator,
String... values)
Generate a new string where each non empty value is separated by the separator. |
static String |
makeFirstLetterLowercase(String id)
|
static String |
makeFirstLetterUppercase(String id)
|
static String |
midpad(String s,
int length)
Pad the beginning and end of the given String with spaces until the String is of the given length. |
static String |
midpad(String s,
int length,
char c)
Pad the beginning and end of the given String with the given character until the result is the desired length. |
static int |
nthIndexOfWord(String s,
String word,
int n)
return the index of the nth occurence of word. -1 if word can't be found n times |
static String |
nthWord(String s,
int nr,
char delimiter)
return the nthWord delimited by a delimiter |
static String |
postpad(String s,
int length)
Pad the end of the given String with spaces until the String is of the given length. |
static String |
postpad(String s,
int length,
char c)
Append the given character to the String until the result is the desired length. |
static String |
prepad(String s,
int length,
char c)
Pre-pend the given character to the String until the result is the desired length. |
static String |
pullToken(StringBuffer buf,
String delim)
Remove a token from a the beginning of a StringBuffer,
and return it. |
static String |
removeChars(String from,
String chars)
Remove any of the characters in chars from the string |
static String |
removeSubstring(String s,
int startIdx,
int endIdx)
snip a portion from a string and return the remainder |
static String |
repeat(String s,
int n)
Repeat string S for N times |
static String |
replace(String strReplaceInThis,
String strReplaceThis,
String strWithThis)
replace function for strings instead of chars |
static String |
replace(String strReplaceInThis,
String strReplaceThis,
String strWithThis,
int fromIdx,
int toIdx)
Replace a substring in a string but only between the specified indexes (substring). |
static String |
replaceFirst(String strReplaceInThis,
String strReplaceThis,
String strWithThis)
replace function for strings instead of chars, only replace first occurence |
static String |
replaceSubstring(String s,
int startIdx,
int endIdx,
String s2)
remove a piece from within a string and insert new at that location |
static String |
reverse(String s)
reverse a string |
static String |
right(String aString,
int len)
equivalent to the basic "right" function |
static List<String> |
splitOnTokens(String s,
List<String> tokens,
boolean includeTokens)
Split the string on any of the provided tokens This method is better than the tokenize methods in regard to ignoring empty fields. |
static List<String> |
splitOnTokens(String s,
String tokens,
boolean includeTokens)
Split on each character |
static byte[] |
stringToByteArray(String str)
Returns a java string as a byte array |
static byte[] |
stringToByteArray(String str,
int offset,
int length)
Returns a java string as a byte array |
static String |
subWords(String s,
int start)
Get the string starting from the start'th word until end. |
static String |
subWords(String s,
int start,
int end)
Get the string starting from the start'th word ending before the end'th word |
static String |
toHexString(byte[] b)
|
static String |
toJavaStringLiteral(String str,
boolean useRaw)
Convert a String into backslash notation (e.g. newline as backslash-n). |
static String[] |
tokenizeDelimitedToArray(String toBeDelimited,
String delimiters)
Tokenize on each character This method has the known issues of Java's StringTokenizer (e.g. skipping empty values) |
static String[] |
tokenizeDelimitedToArray(String toBeDelimited,
String delimiters,
boolean returnDelims)
Return an array of String from a String containing delimited values. |
static String |
toRoman(int num)
Convert an integer to Roman notation |
static String |
translate(String str,
String fromChars,
String toChars)
Translate characters in a string, like the t// operator in perl. |
static String |
unescapeHTML(String s)
Turn any HTML escape entities in the string into characters and return the resulting string. |
static String |
unescapeURL(String aURLFragment)
Synonym for URLDecoder.decode(String, "UTF-8"). |
static String |
unescapeXML(String xml)
Escape characters for text appearing as XML data, between tags. |
static String |
wrap(String text,
int width)
lines may not be longer than X characters (words are cut) |
static String |
wrapApproximate(String aString,
int approximateWidth)
wraps a string to a maximum length by inserting newlines |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
|---|
public static final String SOURCECODE_VERSION
public static final String FILTERCHARS_LOWERLETTERS
public static final String FILTERCHARS_UPPERLETTERS
public static final String FILTERCHARS_DIGITS
public static final String FILTERCHARS_PUNCTUATION
public static final String FILTERCHARS_BACKSLASH
public static final String FILTERCHARS_QUOTES
| Constructor Detail |
|---|
public StringUtil()
| Method Detail |
|---|
public static String[] tokenizeDelimitedToArray(String toBeDelimited,
String delimiters,
boolean returnDelims)
delimited - the String value to tokenizedelimiters - the delimiter ("," or ";" for example)
public static String[] tokenizeDelimitedToArray(String toBeDelimited,
String delimiters)
toBeDelimited - delimiters -
public static List<String> splitOnTokens(String s,
List<String> tokens,
boolean includeTokens)
s - the string to be splittokens - each string is used as a token (not its individual characters)includeTokens - include the tokens in the resulting segments
public static List<String> splitOnTokens(String s,
String tokens,
boolean includeTokens)
s - tokens - includeTokens -
public static byte[] stringToByteArray(String str)
public static byte[] stringToByteArray(String str,
int offset,
int length)
public static String byteArrayToString(byte[] ba,
int offset,
int len)
public static String byteArrayToString(byte[] ba)
public static String wrapApproximate(String aString,
int approximateWidth)
aString - approximateWidth -
public static String wrap(String text,
int width)
public static String left(String aString,
int len)
aString - len -
public static String right(String aString,
int len)
aString - len -
public static String replace(String strReplaceInThis,
String strReplaceThis,
String strWithThis)
strReplaceInThis - in this stringstrReplaceThis - this orignal textstrWithThis - with this text
public static String replaceFirst(String strReplaceInThis,
String strReplaceThis,
String strWithThis)
strReplaceInThis - in this stringstrReplaceThis - this orignal textstrWithThis - with this text
public static String replace(String strReplaceInThis,
String strReplaceThis,
String strWithThis,
int fromIdx,
int toIdx)
strReplaceInThis - strReplaceThis - strWithThis - fromIdx - toIdx -
public static String escapeXML(String text)
public static String unescapeXML(String xml)
public static String escapeURL(String aURLFragment)
Used to ensure that HTTP query strings are in proper form, by escaping special characters such as spaces.
An example use case for this method is a login scheme in which, after successful login, the user is redirected to the "original" target destination. Such a target might be passed around as a request parameter. Such a request parameter will have a URL as its value, as in "LoginTarget=Blah.jsp?this=that&blah=boo", and would need to be URL-encoded in order to escape its special characters.
It is important to note that if a query string appears in an HREF attribute, then there are two issues - ensuring the query string is valid HTTP (it is URL-encoded), and ensuring it is valid HTML (ensuring the ampersand is escaped).
public static String unescapeURL(String aURLFragment)
public static String escapeHTMLTag(String aTagFragment)
The escaped characters are :
Use cases for this method include :
public static String escapeRegex(String aRegexFragment)
The escaped characters include :
public static String escapeHTML(String s)
Any data that will appear as text on a web page should be be escaped. This is especially important for data that comes from untrusted sources such as Internet users. A common mistake in CGI programming is to ask a user for data and then put that data on a web page. For example:
Server: What is your name? User: <b>Joe<b> Server: Hello Joe, WelcomeIf the name is put on the page without checking that it doesn't contain HTML code or without sanitizing that HTML code, the user could reformat the page, insert scripts, and control the the content on your web server.
This method will replace HTML characters such as > with their HTML entity reference (>) so that the html parser will be sure to interpret them as plain text rather than HTML or script.
This method should be used for both data to be displayed in text
in the html document, and data put in form elements. For example:
<html><body>This in not a <tag>
in HTML</body></html>
and
<form><input type="hidden" name="date" value="This data could
be "malicious""></form>
In the second example, the form data would be properly be resubmitted
to your cgi script in the URLEncoded format:
This data could be %22malicious%22
s - String to be escaped
NullPointerException - if s is null.public static String unescapeHTML(String s)
s - String to be unescaped.
NullPointerException - if s is null.public static String escapeSQL(String s)
Any data that will be put in an SQL query should be be escaped. This is especially important for data that comes from untrusted sources such as Internet users.
For example if you had the following SQL query:
"SELECT * FROM addresses WHERE name='" + name + "' AND private='N'"
Without this function a user could give " OR 1=1 OR ''='"
as their name causing the query to be:
"SELECT * FROM addresses WHERE name='' OR 1=1 OR ''='' AND private='N'"
which will give all addresses, including private ones.
Correct usage would be:
"SELECT * FROM addresses WHERE name='" + StringHelper.escapeSQL(name) + "' AND private='N'"
Another way to avoid this problem is to use a PreparedStatement with appropriate placeholders.
s - String to be escaped
NullPointerException - if s is null.public static String escapeJavaLiteral(String s)
s - String to be escaped
public static String prepad(String s,
int length,
char c)
If a String is longer than the desired length, it will not be truncated, however no padding will be added. Most notably this can be used to generate leading zero's: prepad("" + some_int_being_one, 5, '0') results in "00001".
s - String to be padded.length - desired length of result.c - padding character.
NullPointerException - if s is null.
public static String postpad(String s,
int length)
If a String is longer than the desired length, it will not be truncated, however no padding will be added.
s - String to be padded.length - desired length of result.
NullPointerException - if s is null.
public static String postpad(String s,
int length,
char c)
If a String is longer than the desired length, it will not be truncated, however no padding will be added.
s - String to be padded.length - desired length of result.c - padding character.
NullPointerException - if s is null.
public static String midpad(String s,
int length)
If the number of characters to pad is even, then the padding will be split evenly between the beginning and end, otherwise, the extra character will be added to the end.
If a String is longer than the desired length, it will not be truncated, however no padding will be added.
s - String to be padded.length - desired length of result.
NullPointerException - if s is null.
public static String repeat(String s,
int n)
s - n -
public static String midpad(String s,
int length,
char c)
If the number of characters to pad is even, then the padding will be split evenly between the beginning and end, otherwise, the extra character will be added to the end.
If a String is longer than the desired length, it will not be truncated, however no padding will be added.
s - String to be padded.length - desired length of result.c - padding character.
NullPointerException - if s is null.public static String toHexString(byte[] b)
public static String byteToHex(byte b)
b -
public static String byteToHex(byte[] b)
b -
public static String charToHex(char c)
c -
public static boolean isMatch(String pattern,
String string)
pattern - the wildcard pattern to usestring - the string to check against pattern
public static String subWords(String s,
int start)
s - string that contains words separated by blanks
public static String subWords(String s,
int start,
int end)
public static String nthWord(String s,
int nr,
char delimiter)
public static String firstWord(String s)
public static int nthIndexOfWord(String s,
String word,
int n)
public static String escapeString(String in)
public static String escapeForSQL(String in)
public static String flattenString(String in)
public static int countWords(String s,
String delimiter)
public static String translate(String str,
String fromChars,
String toChars)
public static String deleteChars(String str,
String chars)
public static String pullToken(StringBuffer buf,
String delim)
StringBuffer,
and return it. The delim argument is a string
of possible characters that may ends the token.
This method does not return an empty ("") string - instead
null is returned.
This is a "helper" method, should probably be found in some other class. Let me know if you find a suitable replacement.
buf - the line with words to remove a word fromdelim - string of characters that may end token
public static boolean contains(String str,
String sub)
This method is provided merely for improved code
readability. It is equivalent to
str.indexOf(sub) != -1.
public static boolean contains(String str,
char chr)
This method is provided merely for improved code
readability. It is equivalent to
str.indexOf(chr) != -1.
public static String toJavaStringLiteral(String str,
boolean useRaw)
str - useRaw -
public static String fromJavaStringLiteral(String str)
str - useRaw -
public static String filter(String original,
String filter)
original - filter -
public static String replaceSubstring(String s,
int startIdx,
int endIdx,
String s2)
s - startIdx - endIdx -
public static String removeSubstring(String s,
int startIdx,
int endIdx)
s - startIdx - endIdx -
public static String insertAt(String s,
int startIdx,
String s2)
s - startIdx - s2 -
public static String reverse(String s)
public static String toRoman(int num)
num -
public static String convertStandardTypesToString(Object o)
s - c -
public static Object convertStringToStandardTypes(String s,
Class c)
s - c -
public static String ifNull(String s,
String d)
s - d -
public static String ifEmpty(String s,
String d)
s - d -
public static boolean isEmptyWhitespace(String s)
s -
public static boolean isNotEmptyWhitespace(String s)
s -
public static boolean isEmpty(String s)
s -
public static boolean isNotEmpty(String s)
s -
public static String removeChars(String from,
String chars)
from - chars -
public static String filterChars(String from,
String chars)
from - chars - public static boolean equalsTrueInSomeForm(String s)
s -
public static boolean equalsTrueInSomeForm(String s,
boolean nullOrEmptyValue)
s - nullOrEmptyValue -
public static String makeFirstLetterLowercase(String id)
id -
public static String makeFirstLetterUppercase(String id)
id -
public static int count(String text,
String pattern)
count("ababababab", "abab") returns 2.
public static String firstCharacterUppercase(String s)
s -
public static String firstCharacterLowercase(String s)
s -
public static String makeCSVOfNonEmpty(String separator,
String... values)
separator - values -
public static String makeCSV(String separator,
String... values)
separator - values -
public static boolean isDecimal(String s)
s -
public static boolean isInteger(String s)
s -
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||