📄 stringutils.java
字号:
* This must be smaller than length and can be -1 if no minLength is wanted * @return a substring of <code>string</code> whose length is less than or * equal to <code>length</code>, and that is chopped at whitespace. */ public static final String chopAtWord(String string, int length, int minLength) { // guard clauses if (length < 2) { throw new IllegalArgumentException("Length specified (" + length + ") must be > 2"); } else if (minLength >= length) { throw new IllegalArgumentException("minLength must be smaller than length"); } int sLength = (string == null) ? -1 : string.length(); // shortcircuit clauses if (sLength < 1) { return string; } // minLength specified, string is smaller than the minLength, return the string else if (minLength != -1 && sLength < minLength) { return string; } // no minLength specified, string is smaller than length else if (minLength == -1 && sLength < length) { return string; } char [] charArray = string.toCharArray(); // String is longer than the length specified, attempt to find a newline // or a space if (sLength > length) { sLength = length; // First check if there is a newline character before length; if so, // chop word there. for (int i = 0; i < sLength - 1; i++) { // Windows if (charArray[i] == '\r' && charArray[i + 1] == '\n') { return string.substring(0, i + 1); } // Unix else if (charArray[i] == '\n') { return string.substring(0, i); } } // Also check boundary case of Unix newline if (charArray[sLength - 1] == '\n') { return string.substring(0, sLength - 1); } // No newline, so chop at the first whitespace. for (int i = sLength - 1; i > 0; i--) { if (charArray[i] == ' ') { return string.substring(0, i).trim(); } } } // String is shorter than length but longer than minLength, // make sure there is a space in the string before minLength else if (minLength != -1 && sLength > minLength) { for (int i = 0; i < minLength; i++) { if (charArray[i] == ' ') { return string; } } } // Did not find a word boundary, so return a string at the min length, if a min // length was specified: if (minLength > -1 && minLength <= string.length()) { 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 * at the specified index in the argument or before. However, if there is a * newline character before <code>length</code>, the String will be chopped * there. If no newline or whitespace is found in <code>string</code> up to * the index <code>length</code>, the String will chopped at <code>length</code>. * <p> * For example, chopAtWord("This is a nice String", 10) will return * "This is a" which is the first word boundary less than or equal to 10 * characters into the original String. * * @param string the String to chop. * @param length the index in <code>string</code> to start looking for a * whitespace boundary at. * @return a substring of <code>string</code> whose length is less than or * 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. * For example, passing in "This is a quick test a test", "{a,test}" and 5 would return a string * of "This is a quick" - that's 5 characters (or to the end of the word, whichever * is greater) on either side of "a". Also, since {a,test} is passed in a "a" is found * first in the string, we base the substring off of the position of "a". The wordList is * really just a list of strings to try - the first one found is used.<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 null. */ public static String chopAtWordsAround(String input, String[] wordList, int numChars) { if (input == null || "".equals(input.trim()) || wordList == null || wordList.length == 0 || numChars == 0) { return null; } 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> * are split apart at the earliest wordbreak or at maxLength, whichever is * sooner. If the width specified is less than 5 or greater than the input * Strings length the string will be returned as is. * <p> * Please note that this method can be lossy - trailing spaces on wrapped * 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(); } // Create a regular expression engine that is used by the highlightWords // method below. private static Perl5Util perl5Util = new Perl5Util(); /** * Highlights words in a string. Words matching ignores case. The actual * higlighting method is specified with the start and end higlight tags. * Those might be beginning and ending HTML bold tags, or anything else.<p> * * This method is under the Jive Open Source Software License and was * 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) { //Log.info("String is " + string); if (string == null || words == null || startHighlight == null || endHighlight == null) { return null; } StringBuffer regexp = new StringBuffer(); // Iterate through each word and generate a word list for the regexp. for (int x = 0; x < words.length; x++) { // Escape "|" and "/" and "?" to keep us out of trouble in our regexp. words[x] = perl5Util.substitute("s#([\\?\\|\\/\\.])#\\\\$1#g", words[x]); regexp.append(words[x]); if (x != words.length -1) { regexp.append("|"); } } // Escape the regular expression delimiter ("/"). startHighlight = perl5Util.substitute("s#\\/#\\\\/#g", startHighlight); endHighlight = perl5Util.substitute("s#\\/#\\\\/#g", endHighlight); // don't highlight inside of < .. >// String brackets = "(^|[\\w\\s\\W]*?)([\\<]{1}.*?[\\>]{1})([\\w\\s\\W]*?|$)";//// Perl5Compiler compiler = new Perl5Compiler();// Perl5Matcher matcher = new Perl5Matcher();// PatternMatcherInput input = new PatternMatcherInput(string);// Pattern pattern = null;// MatchResult result = null;// StringBuffer toReturn = new StringBuffer(string.length() + 100);//// // Attempt to compile the pattern.// try {// pattern = compiler.compile(brackets,// Perl5Compiler.CASE_INSENSITIVE_MASK);// }// catch(MalformedPatternException e) { Log.error(e); }//// if (matcher.contains(string, pattern)) {// // go through matches// // not zero indexed!// while (matcher.contains(input, pattern)) {// // fetch match that was found.// result = matcher.getMatch();//// Log.error("first group was " + result.group(1));//// Log.error("second group was " + result.group(2));//// Log.error("third group was " + result.group(3));//// // first part - we want to substitute this part// StringBuffer temp = new StringBuffer(regexp.toString());// temp.insert(0, "s/\\b(");// // The word list is here already, so just append the rest.// temp.append(")\\b/");// temp.append(startHighlight);// temp.append("$1");// temp.append(endHighlight);// temp.append("/igm");// toReturn.append(perl5Util.substitute(temp.toString(), result.group(1)));//// // tag - don't substitute// toReturn.append(result.group(2));//// // last part - substitute// temp = new StringBuffer(regexp.toString());// temp = new StringBuffer();// temp.insert(0, "s/\\b(");// // The word list is here already, so just append the rest.// temp.append(")\\b/");// temp.append(startHighlight);// temp.append("$1");// temp.append(endHighlight);// temp.append("/igm");// toReturn.append(perl5Util.substitute(temp.toString(), result.group(3)));
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -