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.regex.Pattern;
29 public class StringUtils
31 private static final Pattern DELIMITERS_PATTERN = Pattern
32 .compile(".*='[^']*(?!')");
34 private static final char PERCENT = '%';
36 private static final boolean DEBUG = false;
39 * URL encoded characters, indexed by char value
40 * e.g. urlEncodings['='] = urlEncodings[61] = "%3D"
42 private static String[] urlEncodings = new String[255];
45 * Returns a new character array, after inserting characters into the given
49 * the character array to insert into
51 * the 0-based position for insertion
53 * the number of characters to insert
55 * the character to insert
57 public static final char[] insertCharAt(char[] in, int position,
60 char[] tmp = new char[in.length + count];
62 if (position >= in.length)
64 System.arraycopy(in, 0, tmp, 0, in.length);
69 System.arraycopy(in, 0, tmp, 0, position);
79 if (position < in.length)
81 System.arraycopy(in, position, tmp, index, in.length - position);
95 public static final char[] deleteChars(char[] in, int from, int to)
97 if (from >= in.length || from < 0)
106 tmp = new char[from];
107 System.arraycopy(in, 0, tmp, 0, from);
112 tmp = new char[in.length - to + from];
113 System.arraycopy(in, 0, tmp, 0, from);
114 System.arraycopy(in, to, tmp, from, in.length - to);
120 * Returns the last part of 'input' after the last occurrence of 'token'. For
121 * example to extract only the filename from a full path or URL.
125 * a delimiter which must be in regular expression format
128 public static String getLastToken(String input, String token)
138 String[] st = input.split(token);
139 return st[st.length - 1];
143 * Parses the input string into components separated by the delimiter. Unlike
144 * String.split(), this method will ignore occurrences of the delimiter which
145 * are nested within single quotes in name-value pair values, e.g. a='b,c'.
149 * @return elements separated by separator
151 public static String[] separatorListToArray(String input,
154 int seplen = delimiter.length();
155 if (input == null || input.equals("") || input.equals(delimiter))
159 List<String> jv = new ArrayList<>();
160 int cp = 0, pos, escape;
161 boolean wasescaped = false, wasquoted = false;
162 String lstitem = null;
163 while ((pos = input.indexOf(delimiter, cp)) >= cp)
165 escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
166 if (wasescaped || wasquoted)
168 // append to previous pos
169 jv.set(jv.size() - 1, lstitem = lstitem + delimiter
170 + input.substring(cp, pos + escape));
174 jv.add(lstitem = input.substring(cp, pos + escape));
177 wasescaped = escape == -1;
178 // last separator may be in an unmatched quote
179 wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
181 if (cp < input.length())
183 String c = input.substring(cp);
184 if (wasescaped || wasquoted)
186 // append final separator
187 jv.set(jv.size() - 1, lstitem + delimiter + c);
191 if (!c.equals(delimiter))
199 String[] v = jv.toArray(new String[jv.size()]);
203 System.err.println("Array from '" + delimiter
204 + "' separated List:\n" + v.length);
205 for (int i = 0; i < v.length; i++)
207 System.err.println("item " + i + " '" + v[i] + "'");
215 "Empty Array from '" + delimiter + "' separated List");
221 * Returns a string which contains the list elements delimited by the
222 * separator. Null items are ignored. If the input is null or has length zero,
223 * a single delimiter is returned.
227 * @return concatenated string
229 public static String arrayToSeparatorList(String[] list, String separator)
231 StringBuffer v = new StringBuffer();
232 if (list != null && list.length > 0)
234 for (int i = 0, iSize = list.length; i < iSize; i++)
242 // TODO - escape any separator values in list[i]
249 .println("Returning '" + separator + "' separated List:\n");
250 System.err.println(v);
257 "Returning empty '" + separator + "' separated List\n");
259 return "" + separator;
263 * Converts a list to a string with a delimiter before each term except the
264 * first. Returns an empty string given a null or zero-length argument. This
265 * can be replaced with StringJoiner in Java 8.
271 public static String listToDelimitedString(List<String> terms,
274 StringBuilder sb = new StringBuilder(32);
275 if (terms != null && !terms.isEmpty())
277 boolean appended = false;
278 for (String term : terms)
288 return sb.toString();
292 * Convenience method to parse a string to an integer, returning 0 if the
293 * input is null or not a valid integer
298 public static int parseInt(String s)
301 if (s != null && s.length() > 0)
305 result = Integer.parseInt(s);
306 } catch (NumberFormatException ex)
314 * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
315 * the first version precedes, is equal to, or follows the second
321 public static int compareVersions(String v1, String v2)
323 return compareVersions(v1, v2, null);
327 * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
328 * the first version precedes, is equal to, or follows the second
332 * @param pointSeparator
333 * a string used to delimit point increments in sub-tokens of the
337 public static int compareVersions(String v1, String v2,
338 String pointSeparator)
340 if (v1 == null || v2 == null)
344 String[] toks1 = v1.split("\\.");
345 String[] toks2 = v2.split("\\.");
347 for (; i < toks1.length; i++)
349 if (i >= toks2.length)
356 String tok1 = toks1[i];
357 String tok2 = toks2[i];
358 if (pointSeparator != null)
361 * convert e.g. 5b2 into decimal 5.2 for comparison purposes
363 tok1 = tok1.replace(pointSeparator, ".");
364 tok2 = tok2.replace(pointSeparator, ".");
368 float f1 = Float.valueOf(tok1);
369 float f2 = Float.valueOf(tok2);
370 int comp = Float.compare(f1, f2);
375 } catch (NumberFormatException e)
378 .println("Invalid version format found: " + e.getMessage());
383 if (i < toks2.length)
392 * same length, all tokens match
398 * Converts the string to all lower-case except the first character which is
404 public static String toSentenceCase(String s)
412 return s.toUpperCase();
414 return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
418 * A helper method that strips off any leading or trailing html and body tags.
419 * If no html tag is found, then also html-encodes angle bracket characters.
424 public static String stripHtmlTags(String text)
430 String tmp2up = text.toUpperCase();
431 int startTag = tmp2up.indexOf("<HTML>");
434 text = text.substring(startTag + 6);
435 tmp2up = tmp2up.substring(startTag + 6);
437 // is omission of "<BODY>" intentional here??
438 int endTag = tmp2up.indexOf("</BODY>");
441 text = text.substring(0, endTag);
442 tmp2up = tmp2up.substring(0, endTag);
444 endTag = tmp2up.indexOf("</HTML>");
447 text = text.substring(0, endTag);
450 if (startTag == -1 && (text.contains("<") || text.contains(">")))
452 text = text.replaceAll("<", "<");
453 text = text.replaceAll(">", ">");
459 * Answers the input string with any occurrences of the 'encodeable' characters
460 * replaced by their URL encoding
466 public static String urlEncode(String s, String encodable)
468 if (s == null || s.isEmpty())
474 * do % encoding first, as otherwise it may double-encode!
476 if (encodable.indexOf(PERCENT) != -1)
478 s = urlEncode(s, PERCENT);
481 for (char c : encodable.toCharArray())
492 * Answers the input string with any occurrences of {@code c} replaced with
493 * their url encoding. Answers the input string if it is unchanged.
499 static String urlEncode(String s, char c)
501 String decoded = String.valueOf(c);
502 if (s.indexOf(decoded) != -1)
504 String encoded = getUrlEncoding(c);
505 if (!encoded.equals(decoded))
507 s = s.replace(decoded, encoded);
514 * Answers the input string with any occurrences of the specified (unencoded)
515 * characters replaced by their URL decoding.
517 * Example: {@code urlDecode("a%3Db%3Bc", "-;=,")} should answer
524 public static String urlDecode(String s, String encodable)
526 if (s == null || s.isEmpty())
531 for (char c : encodable.toCharArray())
533 String encoded = getUrlEncoding(c);
534 if (s.indexOf(encoded) != -1)
536 String decoded = String.valueOf(c);
537 s = s.replace(encoded, decoded);
544 * Does a lazy lookup of the url encoding of the given character, saving the
545 * value for repeat lookups
550 private static String getUrlEncoding(char c)
552 if (c < 0 || c >= urlEncodings.length)
554 return String.valueOf(c);
557 String enc = urlEncodings[c];
562 enc = urlEncodings[c] = URLEncoder.encode(String.valueOf(c),
564 } catch (UnsupportedEncodingException e)
566 enc = urlEncodings[c] = String.valueOf(c);