2 * Basic String manipulation utilities.
3 * (c) Winterwell 2010 and ThinkTank Mathematics 2007
5 package winterwell.markdown;
7 import java.math.BigInteger;
8 import java.security.MessageDigest;
9 import java.security.NoSuchAlgorithmException;
10 import java.util.ArrayList;
11 import java.util.List;
12 import java.util.regex.Pattern;
14 import winterwell.utils.Mutable;
15 import winterwell.utils.containers.Pair;
18 * A collection of general-purpose String handling methods.
20 * @author daniel.winterstein
22 public final class StringMethods {
25 * Removes xml tags, comment blocks and script blocks.
28 * @return the page with all xml tags removed.
30 public static String stripTags(String page) {
31 // This code is rather ugly, but it does the job
32 StringBuilder stripped = new StringBuilder(page.length());
33 boolean inTag = false;
34 // Comment blocks and script blocks are given special treatment
35 boolean inComment = false;
36 boolean inScript = false;
37 // Go through the text
38 for (int i = 0; i < page.length(); i++) {
39 char c = page.charAt(i);
40 // First check whether we are ignoring text
44 } else if (inComment) {
45 if (c == '>' && page.charAt(i - 1) == '-'
46 && page.charAt(i - 1) == '-') {
49 } else if (inScript) {
50 if (c == '>' && page.substring(i - 7, i).equals("/script")) {
54 // Check for the start of a tag - looks for '<' followed by any
55 // non-whitespace character
56 if (c == '<' && !Character.isWhitespace(page.charAt(i + 1))) {
57 // Comment, script-block or tag?
58 if (page.charAt(i + 1) == '!' && page.charAt(i + 2) == '-'
59 && page.charAt(i + 3) == '-') {
61 } else if (i + 8 < page.length()
62 && page.substring(i + 1, i + 7).equals("script")) {
66 inTag = true; // Normal tag by default
68 // Append all non-tag chars
73 return stripped.toString();
77 * The local line-end string. \n on unix, \r\n on windows, \r on mac.
79 public static final String LINEEND = System.getProperty("line.separator");
83 * @return A version of s where the first letter is uppercase and all others
86 public static final String capitalise(final String s) {
87 return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
91 * Convert all line breaks into the system line break.
93 public static final String convertLineBreaks(String text) {
94 return convertLineBreaks(text, LINEEND);
98 * Convert all line breaks into the specified line break.
100 public static final String convertLineBreaks(String text, String br) {
101 text = text.replaceAll("\r\n", br);
102 text = text.replaceAll("\r", br);
103 text = text.replaceAll("\n", br);
110 * @return the number of times character appears in the string
111 * @author Sam Halliday
113 static public int countCharsInString(String string, char character) {
115 for (char c : string.toCharArray()) {
116 if (c == character) {
126 * <code>findEnclosingRegion("text with a [region] inside", 15, '[', ']')</code>
133 * @return the smallest enclosed region (including start and end chars, the
134 * 1st number is inclusive, the 2nd exclusive), or null if none. So
135 * text.subString(start,end) is the specified region
137 public static Pair<Integer> findEnclosingRegion(String text, int offset,
138 char startMarker, char endMarker) {
140 int end = findEnclosingRegion2(text, offset, endMarker, 1);
143 end++; // end is exclusive
145 int start = findEnclosingRegion2(text, offset, startMarker, -1);
149 assert text.substring(start, end).charAt(0) == startMarker;
150 assert text.substring(start, end).endsWith("" + endMarker);
152 return new Pair<Integer>(start, end);
155 private static int findEnclosingRegion2(String text, int offset,
156 char endMarker, int direction) {
157 while (offset > -1 && offset < text.length()) {
158 char c = text.charAt(offset);
167 * A convenience wrapper for
168 * {@link #findEnclosingRegion(String, int, char, char)} E.g. <code>
169 findEnclosingRegion("text with a [region] inside", 15, '[', ']') .equals("[region]");
176 * @return the smallest enclosed region (including start and end chars), or
179 public static String findEnclosingText(String text, int offset,
180 char startMarker, char endMarker) {
181 Pair<Integer> region = findEnclosingRegion(text, offset, startMarker,
185 String s = text.substring(region.first, region.second);
190 * Format a block of text to use the given line-width. I.e. adjust the line
191 * breaks. Also known as <i>hard</i> line-wrapping. Paragraphs are
192 * recognised by a line of blank space between them (e.g. two returns).
194 * Note: a side-effect of this method is that it converts all line-breaks
195 * into the local system's line-breaks. E.g. on Windows, \n will become \r\n
200 * The number of columns in a line. Typically 78 or 80.
201 * @param respectLeadingCharacters
202 * Can be null. If set, the specified leading characters will be
203 * copied if the line is split. Use with " \t" to keep indented
204 * paragraphs properly indented. Use with "> \t" to also handle
205 * email-style quoting. Note that respected leading characters
206 * receive no special treatment when they are used inside a
208 * @return A copy of text, formatted to the given line-width.
210 * TODO: recognise paragraphs by changes in the respected leading
213 public static String format(String text, int lineWidth, int tabWidth,
214 String respectLeadingCharacters) {
215 // Switch to Linux line breaks for easier internal workings
216 text = convertLineBreaks(text, "\n");
218 List<String> paras = format2_splitParagraphs(text,
219 respectLeadingCharacters);
221 StringBuilder sb = new StringBuilder(text.length() + 10);
222 for (String p : paras) {
223 String fp = format3_oneParagraph(p, lineWidth, tabWidth,
224 respectLeadingCharacters);
226 // Paragraphs end with a double line break
229 // Pop the last line breaks
230 sb.delete(sb.length() - 2, sb.length());
231 // Convert line breaks to system ones
232 text = convertLineBreaks(sb.toString());
237 private static List<String> format2_splitParagraphs(String text,
238 String respectLeadingCharacters) {
239 List<String> paras = new ArrayList<String>();
240 Mutable.Int index = new Mutable.Int(0);
241 // TODO The characters prefacing this paragraph
242 String leadingChars = "";
243 while (index.value < text.length()) {
245 boolean inSpace = false;
246 int start = index.value;
247 while (index.value < text.length()) {
248 char c = text.charAt(index.value);
250 if (!Character.isWhitespace(c)) {
255 if (c == '\r' || c == '\n') {
256 // // Handle MS Windows 2 character \r\n line breaks
257 // if (index.value < text.length()) {
258 // char c2 = text.charAt(index.value);
259 // if (c=='\r' && c2=='\n') index.value++; // Push on past
260 // the 2nd line break char
262 // Double line end - indicating a paragraph break
267 // TODO Other paragraph markers, spotted by a change in
270 String p = text.substring(start, index.value);
278 * Format a block of text to fit the given line width
283 * @param respectLeadingCharacters
286 private static String format3_oneParagraph(String p, int lineWidth,
287 int tabWidth, String respectLeadingCharacters) {
288 // Collect the reformatted paragraph
289 StringBuilder sb = new StringBuilder(p.length() + 10); // Allow for
292 // Get respected leading chars
293 String leadingChars = format4_getLeadingChars(p,
294 respectLeadingCharacters);
296 sb.append(leadingChars);
297 int lineLength = leadingChars.length();
298 int index = leadingChars.length();
300 while (index < p.length()) {
302 StringBuilder word = new StringBuilder();
303 char c = p.charAt(index);
305 while (!Character.isWhitespace(c)) {
307 if (index == p.length())
312 // Break the line if the word will not fit
313 if (lineLength + word.length() > lineWidth && lineLength != 0) {
315 sb.append('\n'); // lineEnd(sb);
317 sb.append(leadingChars);
318 lineLength = leadingChars.length();
322 lineLength += word.length();
323 // Add the whitespace
324 if (index != p.length() && lineLength < lineWidth) {
329 lineLength += (c == '\t') ? tabWidth : 1;
335 return sb.toString();
341 * @param respectLeadingCharacters
343 * @return The characters at the beginning of text which are respected. E.g.
344 * ("> Hello", " \t>") --> "> "
346 private static String format4_getLeadingChars(String text,
347 String respectLeadingCharacters) {
348 if (respectLeadingCharacters == null)
350 // Line-breaks cannot be respected
351 assert respectLeadingCharacters.indexOf('\n') == -1;
352 // Look for the first non-respected char
353 for (int i = 0; i < text.length(); i++) {
354 char c = text.charAt(i);
355 if (respectLeadingCharacters.indexOf(c) == -1) {
356 // Return the previous chars
357 return text.substring(0, i);
360 // All chars are respected
365 * Ensure that line ends with the right line-end character(s)
367 public static final String lineEnd(String line) {
368 // strip possibly inappropriate line-endings
369 if (line.endsWith("\n")) {
370 line = line.substring(0, line.length() - 1);
372 if (line.endsWith("\r\n")) {
373 line = line.substring(0, line.length() - 2);
375 if (line.endsWith("\r")) {
376 line = line.substring(0, line.length() - 1);
378 // add in proper line end
379 if (!line.endsWith(LINEEND)) {
386 * Ensure that line ends with the right line-end character(s). This is more
387 * efficient than the version for Strings.
391 public static final void lineEnd(final StringBuilder line) {
392 if (line.length() == 0) {
393 line.append(LINEEND);
396 // strip possibly inappropriate line-endings
397 final char last = line.charAt(line.length() - 1);
399 if ((line.length() > 1) && (line.charAt(line.length() - 2) == '\r')) {
401 line.replace(line.length() - 2, line.length(), LINEEND);
404 line.replace(line.length() - 1, line.length(), LINEEND);
408 line.replace(line.length() - 1, line.length(), LINEEND);
411 line.append(LINEEND);
419 * @return the MD5 sum of the string using the default charset. Null if
420 * there was an error in calculating the hash.
421 * @author Sam Halliday
423 public static String md5Hash(String string) {
424 MessageDigest md5 = null;
426 md5 = MessageDigest.getInstance("MD5");
427 } catch (NoSuchAlgorithmException e) {
428 // ignore this exception, we know MD5 exists
430 md5.update(string.getBytes());
431 BigInteger hash = new BigInteger(1, md5.digest());
432 return hash.toString(16);
436 * Removes HTML-style tags from a string.
439 * a String from which to remove tags
440 * @return a string with all instances of <.*> removed.
442 public static String removeTags(String s) {
443 StringBuffer sb = new StringBuffer();
444 boolean inTag = false;
445 for (int i = 0; i < s.length(); i++) {
446 char c = s.charAt(i);
454 return sb.toString();
458 * Repeat a character.
462 * @return A String consisting of i x c.
463 * @example assert repeat('-', 5).equals("-----");
465 public static String repeat(Character c, int i) {
466 StringBuilder dashes = new StringBuilder(i);
467 for (int j = 0; j < i; j++)
469 return dashes.toString();
473 * Split a piece of text into separate lines. The line breaks are left at
474 * the end of each line.
477 * @return The individual lines in the text.
479 public static List<String> splitLines(String text) {
480 List<String> lines = new ArrayList<String>();
483 for (int i = 0; i < text.length(); i++) {
484 char c = text.charAt(i);
485 if (c == '\r' || c == '\n') {
486 // Handle MS Windows 2 character \r\n line breaks
487 if (i + 1 < text.length()) {
488 char c2 = text.charAt(i + 1);
489 if (c == '\r' && c2 == '\n')
492 // Get the line, with the line break
493 String line = text.substring(start, i + 1);
499 if (start != text.length()) {
500 String line = text.substring(start);
507 * Remove <i>trailing</i> whitespace. c.f. String#trim() which removes
508 * leading and trailing whitespace.
512 private static void trimEnd(StringBuilder sb) {
514 // Get the last character
515 int i = sb.length() - 1;
517 return; // Quit if sb is empty
518 char c = sb.charAt(i);
519 if (!Character.isWhitespace(c))
521 sb.deleteCharAt(i); // Remove and continue
526 * Returns true if the string is just whitespace, or empty, or null.
530 public static final boolean whitespace(final String s) {
534 for (int i = 0; i < s.length(); i++) {
535 final char c = s.charAt(i);
536 if (!Character.isWhitespace(c)) {
545 * @return the number of words in text. Uses a crude whitespace
548 public static int wordCount(String text) {
549 String[] bits = text.split("\\W+");
551 for (String string : bits) {
552 if (!whitespace(string)) wc++;