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.Matcher;
29 import java.util.regex.Pattern;
31 public class StringUtils
33 private static final Pattern DELIMITERS_PATTERN = Pattern
34 .compile(".*='[^']*(?!')");
36 private static final char PERCENT = '%';
38 private static final boolean DEBUG = false;
41 * URL encoded characters, indexed by char value
42 * e.g. urlEncodings['='] = urlEncodings[61] = "%3D"
44 private static String[] urlEncodings = new String[255];
47 * Returns a new character array, after inserting characters into the given
51 * the character array to insert into
53 * the 0-based position for insertion
55 * the number of characters to insert
57 * the character to insert
59 public static final char[] insertCharAt(char[] in, int position,
62 char[] tmp = new char[in.length + count];
64 if (position >= in.length)
66 System.arraycopy(in, 0, tmp, 0, in.length);
71 System.arraycopy(in, 0, tmp, 0, position);
81 if (position < in.length)
83 System.arraycopy(in, position, tmp, index, in.length - position);
97 public static final char[] deleteChars(char[] in, int from, int to)
99 if (from >= in.length || from < 0)
108 tmp = new char[from];
109 System.arraycopy(in, 0, tmp, 0, from);
114 tmp = new char[in.length - to + from];
115 System.arraycopy(in, 0, tmp, 0, from);
116 System.arraycopy(in, to, tmp, from, in.length - to);
122 * Returns the last part of 'input' after the last occurrence of 'token'. For
123 * example to extract only the filename from a full path or URL.
127 * a delimiter which must be in regular expression format
130 public static String getLastToken(String input, String token)
140 String[] st = input.split(token);
141 return st[st.length - 1];
145 * Parses the input string into components separated by the delimiter. Unlike
146 * String.split(), this method will ignore occurrences of the delimiter which
147 * are nested within single quotes in name-value pair values, e.g. a='b,c'.
151 * @return elements separated by separator
153 public static String[] separatorListToArray(String input,
156 int seplen = delimiter.length();
157 if (input == null || input.equals("") || input.equals(delimiter))
161 List<String> jv = new ArrayList<>();
162 int cp = 0, pos, escape;
163 boolean wasescaped = false, wasquoted = false;
164 String lstitem = null;
165 while ((pos = input.indexOf(delimiter, cp)) >= cp)
167 escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
168 if (wasescaped || wasquoted)
170 // append to previous pos
171 jv.set(jv.size() - 1, lstitem = lstitem + delimiter
172 + input.substring(cp, pos + escape));
176 jv.add(lstitem = input.substring(cp, pos + escape));
179 wasescaped = escape == -1;
180 // last separator may be in an unmatched quote
181 wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
183 if (cp < input.length())
185 String c = input.substring(cp);
186 if (wasescaped || wasquoted)
188 // append final separator
189 jv.set(jv.size() - 1, lstitem + delimiter + c);
193 if (!c.equals(delimiter))
201 String[] v = jv.toArray(new String[jv.size()]);
205 System.err.println("Array from '" + delimiter
206 + "' separated List:\n" + v.length);
207 for (int i = 0; i < v.length; i++)
209 System.err.println("item " + i + " '" + v[i] + "'");
217 "Empty Array from '" + delimiter + "' separated List");
223 * Returns a string which contains the list elements delimited by the
224 * separator. Null items are ignored. If the input is null or has length zero,
225 * a single delimiter is returned.
229 * @return concatenated string
231 public static String arrayToSeparatorList(String[] list, String separator)
233 StringBuffer v = new StringBuffer();
234 if (list != null && list.length > 0)
236 for (int i = 0, iSize = list.length; i < iSize; i++)
244 // TODO - escape any separator values in list[i]
251 .println("Returning '" + separator + "' separated List:\n");
252 System.err.println(v);
259 "Returning empty '" + separator + "' separated List\n");
261 return "" + separator;
265 * Converts a list to a string with a delimiter before each term except the
266 * first. Returns an empty string given a null or zero-length argument. This
267 * can be replaced with StringJoiner in Java 8.
273 public static String listToDelimitedString(List<String> terms,
276 StringBuilder sb = new StringBuilder(32);
277 if (terms != null && !terms.isEmpty())
279 boolean appended = false;
280 for (String term : terms)
290 return sb.toString();
294 * Convenience method to parse a string to an integer, returning 0 if the
295 * input is null or not a valid integer
300 public static int parseInt(String s)
303 if (s != null && s.length() > 0)
307 result = Integer.parseInt(s);
308 } catch (NumberFormatException ex)
316 * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
317 * the first version precedes, is equal to, or follows the second
323 public static int compareVersions(String v1, String v2)
325 return compareVersions(v1, v2, null);
329 * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
330 * the first version precedes, is equal to, or follows the second
334 * @param pointSeparator
335 * a string used to delimit point increments in sub-tokens of the
339 public static int compareVersions(String v1, String v2,
340 String pointSeparator)
342 if (v1 == null || v2 == null)
346 String[] toks1 = v1.split("\\.");
347 String[] toks2 = v2.split("\\.");
349 for (; i < toks1.length; i++)
351 if (i >= toks2.length)
358 String tok1 = toks1[i];
359 String tok2 = toks2[i];
360 if (pointSeparator != null)
363 * convert e.g. 5b2 into decimal 5.2 for comparison purposes
365 tok1 = tok1.replace(pointSeparator, ".");
366 tok2 = tok2.replace(pointSeparator, ".");
370 float f1 = Float.valueOf(tok1);
371 float f2 = Float.valueOf(tok2);
372 int comp = Float.compare(f1, f2);
377 } catch (NumberFormatException e)
380 .println("Invalid version format found: " + e.getMessage());
385 if (i < toks2.length)
394 * same length, all tokens match
400 * Converts the string to all lower-case except the first character which is
406 public static String toSentenceCase(String s)
414 return s.toUpperCase(Locale.ROOT);
416 return s.substring(0, 1).toUpperCase(Locale.ROOT)
417 + s.substring(1).toLowerCase(Locale.ROOT);
421 * A helper method that strips off any leading or trailing html and body tags.
422 * If no html tag is found, then also html-encodes angle bracket characters.
427 public static String stripHtmlTags(String text)
433 String tmp2up = text.toUpperCase(Locale.ROOT);
434 int startTag = tmp2up.indexOf("<HTML>");
437 text = text.substring(startTag + 6);
438 tmp2up = tmp2up.substring(startTag + 6);
440 // is omission of "<BODY>" intentional here??
441 int endTag = tmp2up.indexOf("</BODY>");
444 text = text.substring(0, endTag);
445 tmp2up = tmp2up.substring(0, endTag);
447 endTag = tmp2up.indexOf("</HTML>");
450 text = text.substring(0, endTag);
453 if (startTag == -1 && (text.contains("<") || text.contains(">")))
455 text = text.replaceAll("<", "<");
456 text = text.replaceAll(">", ">");
462 * Answers the input string with any occurrences of the 'encodeable'
463 * characters replaced by their URL encoding
469 public static String urlEncode(String s, String encodable)
471 if (s == null || s.isEmpty())
477 * do % encoding first, as otherwise it may double-encode!
479 if (encodable.indexOf(PERCENT) != -1)
481 s = urlEncode(s, PERCENT);
484 for (char c : encodable.toCharArray())
495 * Answers the input string with any occurrences of {@code c} replaced with
496 * their url encoding. Answers the input string if it is unchanged.
502 static String urlEncode(String s, char c)
504 String decoded = String.valueOf(c);
505 if (s.indexOf(decoded) != -1)
507 String encoded = getUrlEncoding(c);
508 if (!encoded.equals(decoded))
510 s = s.replace(decoded, encoded);
517 * Answers the input string with any occurrences of the specified (unencoded)
518 * characters replaced by their URL decoding.
520 * Example: {@code urlDecode("a%3Db%3Bc", "-;=,")} should answer
527 public static String urlDecode(String s, String encodable)
529 if (s == null || s.isEmpty())
534 for (char c : encodable.toCharArray())
536 String encoded = getUrlEncoding(c);
537 if (s.indexOf(encoded) != -1)
539 String decoded = String.valueOf(c);
540 s = s.replace(encoded, decoded);
547 * Does a lazy lookup of the url encoding of the given character, saving the
548 * value for repeat lookups
553 private static String getUrlEncoding(char c)
555 if (c < 0 || c >= urlEncodings.length)
557 return String.valueOf(c);
560 String enc = urlEncodings[c];
565 enc = urlEncodings[c] = URLEncoder.encode(String.valueOf(c),
567 } catch (UnsupportedEncodingException e)
569 enc = urlEncodings[c] = String.valueOf(c);
575 public static int firstCharPosIgnoreCase(String text, String chars)
577 int min = text.length() + 1;
578 for (char c : chars.toLowerCase(Locale.ROOT).toCharArray())
580 int i = text.toLowerCase(Locale.ROOT).indexOf(c);
581 if (0 <= i && i < min)
586 return min < text.length() + 1 ? min : -1;
589 public static int indexOfFirstWhitespace(String text)
592 Pattern pat = Pattern.compile("\\s");
593 Matcher m = pat.matcher(text);
602 * implementation of String.replaceLast.
603 * Replaces only the last occurrence of toReplace in string with replacement.
605 public static String replaceLast(String string, String toReplace,
608 int pos = string.lastIndexOf(toReplace);
611 return new StringBuilder().append(string.substring(0, pos))
613 .append(string.substring(pos + toReplace.length()))