2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.io.UnsupportedEncodingException;
24 import java.net.URLEncoder;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.Locale;
28 import java.util.regex.Pattern;
30 public class StringUtils
32 private static final Pattern DELIMITERS_PATTERN = Pattern
33 .compile(".*='[^']*(?!')");
35 private static final char PERCENT = '%';
37 private static final boolean DEBUG = false;
40 * URL encoded characters, indexed by char value
41 * e.g. urlEncodings['='] = urlEncodings[61] = "%3D"
43 private static String[] urlEncodings = new String[255];
46 * Returns a new character array, after inserting characters into the given
50 * the character array to insert into
52 * the 0-based position for insertion
54 * the number of characters to insert
56 * the character to insert
58 public static final char[] insertCharAt(char[] in, int position,
61 char[] tmp = new char[in.length + count];
63 if (position >= in.length)
65 System.arraycopy(in, 0, tmp, 0, in.length);
70 System.arraycopy(in, 0, tmp, 0, position);
80 if (position < in.length)
82 System.arraycopy(in, position, tmp, index, in.length - position);
96 public static final char[] deleteChars(char[] in, int from, int to)
98 if (from >= in.length || from < 0)
107 tmp = new char[from];
108 System.arraycopy(in, 0, tmp, 0, from);
113 tmp = new char[in.length - to + from];
114 System.arraycopy(in, 0, tmp, 0, from);
115 System.arraycopy(in, to, tmp, from, in.length - to);
121 * Returns the last part of 'input' after the last occurrence of 'token'. For
122 * example to extract only the filename from a full path or URL.
126 * a delimiter which must be in regular expression format
129 public static String getLastToken(String input, String token)
139 String[] st = input.split(token);
140 return st[st.length - 1];
144 * Parses the input string into components separated by the delimiter. Unlike
145 * String.split(), this method will ignore occurrences of the delimiter which
146 * are nested within single quotes in name-value pair values, e.g. a='b,c'.
150 * @return elements separated by separator
152 public static String[] separatorListToArray(String input,
155 int seplen = delimiter.length();
156 if (input == null || input.equals("") || input.equals(delimiter))
160 List<String> jv = new ArrayList<>();
161 int cp = 0, pos, escape;
162 boolean wasescaped = false, wasquoted = false;
163 String lstitem = null;
164 while ((pos = input.indexOf(delimiter, cp)) >= cp)
166 escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
167 if (wasescaped || wasquoted)
169 // append to previous pos
170 jv.set(jv.size() - 1, lstitem = lstitem + delimiter
171 + input.substring(cp, pos + escape));
175 jv.add(lstitem = input.substring(cp, pos + escape));
178 wasescaped = escape == -1;
179 // last separator may be in an unmatched quote
180 wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
182 if (cp < input.length())
184 String c = input.substring(cp);
185 if (wasescaped || wasquoted)
187 // append final separator
188 jv.set(jv.size() - 1, lstitem + delimiter + c);
192 if (!c.equals(delimiter))
200 String[] v = jv.toArray(new String[jv.size()]);
204 System.err.println("Array from '" + delimiter
205 + "' separated List:\n" + v.length);
206 for (int i = 0; i < v.length; i++)
208 System.err.println("item " + i + " '" + v[i] + "'");
216 "Empty Array from '" + delimiter + "' separated List");
222 * Returns a string which contains the list elements delimited by the
223 * separator. Null items are ignored. If the input is null or has length zero,
224 * a single delimiter is returned.
228 * @return concatenated string
230 public static String arrayToSeparatorList(String[] list, String separator)
232 StringBuffer v = new StringBuffer();
233 if (list != null && list.length > 0)
235 for (int i = 0, iSize = list.length; i < iSize; i++)
243 // TODO - escape any separator values in list[i]
250 .println("Returning '" + separator + "' separated List:\n");
251 System.err.println(v);
258 "Returning empty '" + separator + "' separated List\n");
260 return "" + separator;
264 * Converts a list to a string with a delimiter before each term except the
265 * first. Returns an empty string given a null or zero-length argument. This
266 * can be replaced with StringJoiner in Java 8.
272 public static String listToDelimitedString(List<String> terms,
275 StringBuilder sb = new StringBuilder(32);
276 if (terms != null && !terms.isEmpty())
278 boolean appended = false;
279 for (String term : terms)
289 return sb.toString();
293 * Convenience method to parse a string to an integer, returning 0 if the
294 * input is null or not a valid integer
299 public static int parseInt(String s)
302 if (s != null && s.length() > 0)
306 result = Integer.parseInt(s);
307 } catch (NumberFormatException ex)
315 * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
316 * the first version precedes, is equal to, or follows the second
322 public static int compareVersions(String v1, String v2)
324 return compareVersions(v1, v2, null);
328 * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
329 * the first version precedes, is equal to, or follows the second
333 * @param pointSeparator
334 * a string used to delimit point increments in sub-tokens of the
338 public static int compareVersions(String v1, String v2,
339 String pointSeparator)
341 if (v1 == null || v2 == null)
345 String[] toks1 = v1.split("\\.");
346 String[] toks2 = v2.split("\\.");
348 for (; i < toks1.length; i++)
350 if (i >= toks2.length)
357 String tok1 = toks1[i];
358 String tok2 = toks2[i];
359 if (pointSeparator != null)
362 * convert e.g. 5b2 into decimal 5.2 for comparison purposes
364 tok1 = tok1.replace(pointSeparator, ".");
365 tok2 = tok2.replace(pointSeparator, ".");
369 float f1 = Float.valueOf(tok1);
370 float f2 = Float.valueOf(tok2);
371 int comp = Float.compare(f1, f2);
376 } catch (NumberFormatException e)
379 .println("Invalid version format found: " + e.getMessage());
384 if (i < toks2.length)
393 * same length, all tokens match
399 * Converts the string to all lower-case except the first character which is
405 public static String toSentenceCase(String s)
413 return s.toUpperCase(Locale.ROOT);
415 return s.substring(0, 1).toUpperCase(Locale.ROOT) + s.substring(1).toLowerCase(Locale.ROOT);
419 * A helper method that strips off any leading or trailing html and body tags.
420 * If no html tag is found, then also html-encodes angle bracket characters.
425 public static String stripHtmlTags(String text)
431 String tmp2up = text.toUpperCase(Locale.ROOT);
432 int startTag = tmp2up.indexOf("<HTML>");
435 text = text.substring(startTag + 6);
436 tmp2up = tmp2up.substring(startTag + 6);
438 // is omission of "<BODY>" intentional here??
439 int endTag = tmp2up.indexOf("</BODY>");
442 text = text.substring(0, endTag);
443 tmp2up = tmp2up.substring(0, endTag);
445 endTag = tmp2up.indexOf("</HTML>");
448 text = text.substring(0, endTag);
451 if (startTag == -1 && (text.contains("<") || text.contains(">")))
453 text = text.replaceAll("<", "<");
454 text = text.replaceAll(">", ">");
460 * Answers the input string with any occurrences of the 'encodeable'
461 * characters replaced by their URL encoding
467 public static String urlEncode(String s, String encodable)
469 if (s == null || s.isEmpty())
475 * do % encoding first, as otherwise it may double-encode!
477 if (encodable.indexOf(PERCENT) != -1)
479 s = urlEncode(s, PERCENT);
482 for (char c : encodable.toCharArray())
493 * Answers the input string with any occurrences of {@code c} replaced with
494 * their url encoding. Answers the input string if it is unchanged.
500 static String urlEncode(String s, char c)
502 String decoded = String.valueOf(c);
503 if (s.indexOf(decoded) != -1)
505 String encoded = getUrlEncoding(c);
506 if (!encoded.equals(decoded))
508 s = s.replace(decoded, encoded);
515 * Answers the input string with any occurrences of the specified (unencoded)
516 * characters replaced by their URL decoding.
518 * Example: {@code urlDecode("a%3Db%3Bc", "-;=,")} should answer
525 public static String urlDecode(String s, String encodable)
527 if (s == null || s.isEmpty())
532 for (char c : encodable.toCharArray())
534 String encoded = getUrlEncoding(c);
535 if (s.indexOf(encoded) != -1)
537 String decoded = String.valueOf(c);
538 s = s.replace(encoded, decoded);
545 * Does a lazy lookup of the url encoding of the given character, saving the
546 * value for repeat lookups
551 private static String getUrlEncoding(char c)
553 if (c < 0 || c >= urlEncodings.length)
555 return String.valueOf(c);
558 String enc = urlEncodings[c];
563 enc = urlEncodings[c] = URLEncoder.encode(String.valueOf(c),
565 } catch (UnsupportedEncodingException e)
567 enc = urlEncodings[c] = String.valueOf(c);
573 public static int firstCharPosIgnoreCase(String text, String chars)
575 int min = text.length() + 1;
576 for (char c : chars.toLowerCase(Locale.ROOT).toCharArray())
578 int i = text.toLowerCase(Locale.ROOT).indexOf(c);
579 if (0 <= i && i < min)
584 return min < text.length() + 1 ? min : -1;