stringutils.java
来自「开源项目openfire的完整源程序」· Java 代码 · 共 2,677 行 · 第 1/5 页
JAVA
2,677 行
return string.substring(0, minLength);
}
// Did not find word boundary or min length so return original String chopped at
// specified length.
return string.substring(0, length);
}
/**
* Intelligently chops a String at a word boundary (whitespace) that occurs
* <p/>
* at the specified index in the argument or before. However, if there is a
* <p/>
* newline character before <code>length</code>, the String will be chopped
* <p/>
* there. If no newline or whitespace is found in <code>string</code> up to
* <p/>
* the index <code>length</code>, the String will chopped at <code>length</code>.
* <p/>
* <p/>
* <p/>
* For example, chopAtWord("This is a nice String", 10) will return
* <p/>
* "This is a" which is the first word boundary less than or equal to 10
* <p/>
* characters into the original String.
*
* @param string the String to chop.
* @param length the index in <code>string</code> to start looking for a
* <p/>
* whitespace boundary at.
* @return a substring of <code>string</code> whose length is less than or
* <p/>
* equal to <code>length</code>, and that is chopped at whitespace.
*/
public static final String chopAtWord(String string, int length) {
return chopAtWord(string, length, -1);
}
/**
* Returns a substring of the given string which represents the words around the given word.
* <p/>
* For example, passing in "This is a quick test a test", "{a,test}" and 5 would return a string
* <p/>
* of "This is a quick" - that's 5 characters (or to the end of the word, whichever
* <p/>
* is greater) on either side of "a". Also, since {a,test} is passed in a "a" is found
* <p/>
* first in the string, we base the substring off of the position of "a". The wordList is
* <p/>
* really just a list of strings to try - the first one found is used.<p>
* <p/>
* <p/>
* <p/>
* Note: The wordList passed in should be lowercase.
*
* @param input The string to parse.
* @param wordList The words to look for - the first one found in the string is used.
* @param numChars The number of characters on either side to include in the chop.
* @return a substring of the given string matching the criteria, otherwise "".
*/
public static String chopAtWordsAround(String input, String[] wordList, int numChars) {
if (input == null || "".equals(input.trim()) || wordList == null
|| wordList.length == 0 || numChars == 0)
{
return "";
}
String lc = input.toLowerCase();
for (int i = 0; i < wordList.length; i++) {
int pos = lc.indexOf(wordList[i]);
if (pos > -1) {
int beginIdx = pos - numChars;
if (beginIdx < 0) {
beginIdx = 0;
}
int endIdx = pos + numChars;
if (endIdx > input.length() - 1) {
endIdx = input.length() - 1;
}
char[] chars = input.toCharArray();
while (beginIdx > 0 && chars[beginIdx] != ' ' && chars[beginIdx] != '\n'
&& chars[beginIdx] != '\r')
{
beginIdx--;
}
while (endIdx < input.length() && chars[endIdx] != ' '
&& chars[endIdx] != '\n' && chars[endIdx] != '\r')
{
endIdx++;
}
return input.substring(beginIdx, endIdx);
}
}
return input.substring(0, (input.length() >= 200) ? 200 : input.length());
}
/**
* Reformats a string where lines that are longer than <tt>width</tt>
* <p/>
* are split apart at the earliest wordbreak or at maxLength, whichever is
* <p/>
* sooner. If the width specified is less than 5 or greater than the input
* <p/>
* Strings length the string will be returned as is.
* <p/>
* <p/>
* <p/>
* Please note that this method can be lossy - trailing spaces on wrapped
* <p/>
* lines may be trimmed.
*
* @param input the String to reformat.
* @param width the maximum length of any one line.
* @return a new String with reformatted as needed.
*/
public static String wordWrap(String input, int width, Locale locale) {
// protect ourselves
if (input == null) {
return "";
}
else if (width < 5) {
return input;
}
else if (width >= input.length()) {
return input;
}
StringBuffer buf = new StringBuffer(input);
boolean endOfLine = false;
int lineStart = 0;
for (int i = 0; i < buf.length(); i++) {
if (buf.charAt(i) == '\n') {
lineStart = i + 1;
endOfLine = true;
}
// handle splitting at width character
if (i > lineStart + width - 1) {
if (!endOfLine) {
int limit = i - lineStart - 1;
BreakIterator breaks = BreakIterator.getLineInstance(locale);
breaks.setText(buf.substring(lineStart, i));
int end = breaks.last();
// if the last character in the search string isn't a space,
// we can't split on it (looks bad). Search for a previous
// break character
if (end == limit + 1) {
if (!Character.isWhitespace(buf.charAt(lineStart + end))) {
end = breaks.preceding(end - 1);
}
}
// if the last character is a space, replace it with a \n
if (end != BreakIterator.DONE && end == limit + 1) {
buf.replace(lineStart + end, lineStart + end + 1, "\n");
lineStart = lineStart + end;
}
// otherwise, just insert a \n
else if (end != BreakIterator.DONE && end != 0) {
buf.insert(lineStart + end, '\n');
lineStart = lineStart + end + 1;
}
else {
buf.insert(i, '\n');
lineStart = i + 1;
}
}
else {
buf.insert(i, '\n');
lineStart = i + 1;
endOfLine = false;
}
}
}
return buf.toString();
}
/**
* Highlights words in a string. Words matching ignores case. The actual
* <p/>
* higlighting method is specified with the start and end higlight tags.
* <p/>
* Those might be beginning and ending HTML bold tags, or anything else.<p>
* <p/>
* <p/>
* <p/>
* This method is under the Jive Open Source Software License and was
* <p/>
* written by Mark Imbriaco.
*
* @param string the String to highlight words in.
* @param words an array of words that should be highlighted in the string.
* @param startHighlight the tag that should be inserted to start highlighting.
* @param endHighlight the tag that should be inserted to end highlighting.
* @return a new String with the specified words highlighted.
*/
public static final String highlightWords(String string, String[] words,
String startHighlight, String endHighlight)
{
if (string == null || words == null || startHighlight == null || endHighlight == null) {
return null;
}
StringBuffer regexp = new StringBuffer();
regexp.append("(?i)\\b(");
// Iterate through each word and generate a word list for the regexp.
for (int x = 0; x < words.length; x++) {
// Escape "$", "|", ".", "/", and "?" to keep us out of trouble in our regexp.
words[x] = words[x].replaceAll("([\\$\\?\\|\\/\\.])", "\\\\$1");
regexp.append(words[x]);
if (x != words.length - 1) {
regexp.append("|");
}
}
regexp.append(")");
return string.replaceAll(regexp.toString(), startHighlight + "$1" + endHighlight);
}
/**
* Escapes all necessary characters in the String so that it can be used
* <p/>
* in an XML doc.
*
* @param string the string to escape.
* @return the string with appropriate characters escaped.
*/
public static final String escapeForXML(String string) {
if (string == null) {
return null;
}
char ch;
int i = 0;
int last = 0;
char[] input = string.toCharArray();
int len = input.length;
StringBuffer out = new StringBuffer((int)(len * 1.3));
for (; i < len; i++) {
ch = input[i];
if (ch > '>') {
continue;
}
else if (ch == '<') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(LT_ENCODE);
}
else if (ch == '&') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(AMP_ENCODE);
}
else if (ch == '"') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(QUOTE_ENCODE);
}
else if (ch == 10 || ch == 13 || ch == 9) {
continue;
}
else if (ch < 32) {
// Disallow all ASCII control characters, except space,
// enter characters and tabs:
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
}
}
if (last == 0) {
return string;
}
if (i > last) {
out.append(input, last, i - last);
}
return out.toString();
}
/**
* Unescapes the String by converting XML escape sequences back into normal
* <p/>
* characters.
*
* @param string the string to unescape.
* @return the string with appropriate characters unescaped.
*/
public static final String unescapeFromXML(String string) {
string = replace(string, "<", "<");
string = replace(string, ">", ">");
string = replace(string, """, "\"");
return replace(string, "&", "&");
}
private static final char[] zeroArray =
"0000000000000000000000000000000000000000000000000000000000000000".toCharArray();
/**
* Pads the supplied String with 0's to the specified length and returns
* <p/>
* the result as a new String. For example, if the initial String is
* <p/>
* "9999" and the desired length is 8, the result would be "00009999".
* <p/>
* This type of padding is useful for creating numerical values that need
* <p/>
* to be stored and sorted as character data. Note: the current
* <p/>
* implementation of this method allows for a maximum <tt>length</tt> of
* <p/>
* 64.
*
* @param string the original String to pad.
* @param length the desired length of the new padded String.
* @return a new String padded with the required number of 0's.
*/
public static final String zeroPadString(String string, int length) {
if (string == null || string.length() > length) {
return string;
}
StringBuffer buf = new StringBuffer(length);
buf.append(zeroArray, 0, length - string.length()).append(string);
return buf.toString();
}
/**
* Formats a Date as a String. Depending on how Dates are defined in the database
* <p/>
* (character data or numberic), the format return will either be a fifteen character long String
* <p/>
* made up of the Date's padded millisecond value, or will simply be the Date's millesecond value.
*
* @return a Date encoded as a String.
*/
public static final String dateToMillis(Date date) {
return Long.toString(date.getTime());
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?