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.util.Locale;
25 import java.io.UnsupportedEncodingException;
26 import java.net.URLEncoder;
27 import java.util.ArrayList;
28 import java.util.List;
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 * Parses the input string into components separated by the delimiter. Unlike
123 * String.split(), this method will ignore occurrences of the delimiter which
124 * are nested within single quotes in name-value pair values, e.g. a='b,c'.
128 * @return elements separated by separator
130 public static String[] separatorListToArray(String input,
133 int seplen = delimiter.length();
134 if (input == null || input.equals("") || input.equals(delimiter))
138 List<String> jv = new ArrayList<>();
139 int cp = 0, pos, escape;
140 boolean wasescaped = false, wasquoted = false;
141 String lstitem = null;
142 while ((pos = input.indexOf(delimiter, cp)) >= cp)
144 escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
145 if (wasescaped || wasquoted)
147 // append to previous pos
148 jv.set(jv.size() - 1, lstitem = lstitem + delimiter
149 + input.substring(cp, pos + escape));
153 jv.add(lstitem = input.substring(cp, pos + escape));
156 wasescaped = escape == -1;
157 // last separator may be in an unmatched quote
158 wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
160 if (cp < input.length())
162 String c = input.substring(cp);
163 if (wasescaped || wasquoted)
165 // append final separator
166 jv.set(jv.size() - 1, lstitem + delimiter + c);
170 if (!c.equals(delimiter))
178 String[] v = jv.toArray(new String[jv.size()]);
182 System.err.println("Array from '" + delimiter
183 + "' separated List:\n" + v.length);
184 for (int i = 0; i < v.length; i++)
186 System.err.println("item " + i + " '" + v[i] + "'");
194 "Empty Array from '" + delimiter + "' separated List");
200 * Returns a string which contains the list elements delimited by the
201 * separator. Null items are ignored. If the input is null or has length zero,
202 * a single delimiter is returned.
206 * @return concatenated string
208 public static String arrayToSeparatorList(String[] list, String separator)
210 StringBuffer v = new StringBuffer();
211 if (list != null && list.length > 0)
213 for (int i = 0, iSize = list.length; i < iSize; i++)
221 // TODO - escape any separator values in list[i]
228 .println("Returning '" + separator + "' separated List:\n");
229 System.err.println(v);
236 "Returning empty '" + separator + "' separated List\n");
238 return "" + separator;
242 * Converts a list to a string with a delimiter before each term except the
243 * first. Returns an empty string given a null or zero-length argument. This
244 * can be replaced with StringJoiner in Java 8.
250 public static String listToDelimitedString(List<String> terms,
253 StringBuilder sb = new StringBuilder(32);
254 if (terms != null && !terms.isEmpty())
256 boolean appended = false;
257 for (String term : terms)
267 return sb.toString();
271 * Convenience method to parse a string to an integer, returning 0 if the
272 * input is null or not a valid integer
277 public static int parseInt(String s)
280 if (s != null && s.length() > 0)
284 result = Integer.parseInt(s);
285 } catch (NumberFormatException ex)
293 * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
294 * the first version precedes, is equal to, or follows the second
300 public static int compareVersions(String v1, String v2)
302 return compareVersions(v1, v2, null);
306 * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
307 * the first version precedes, is equal to, or follows the second
311 * @param pointSeparator
312 * a string used to delimit point increments in sub-tokens of the
316 public static int compareVersions(String v1, String v2,
317 String pointSeparator)
319 if (v1 == null || v2 == null)
323 String[] toks1 = v1.split("\\.");
324 String[] toks2 = v2.split("\\.");
326 for (; i < toks1.length; i++)
328 if (i >= toks2.length)
335 String tok1 = toks1[i];
336 String tok2 = toks2[i];
337 if (pointSeparator != null)
340 * convert e.g. 5b2 into decimal 5.2 for comparison purposes
342 tok1 = tok1.replace(pointSeparator, ".");
343 tok2 = tok2.replace(pointSeparator, ".");
347 float f1 = Float.valueOf(tok1);
348 float f2 = Float.valueOf(tok2);
349 int comp = Float.compare(f1, f2);
354 } catch (NumberFormatException e)
357 .println("Invalid version format found: " + e.getMessage());
362 if (i < toks2.length)
371 * same length, all tokens match
377 * Converts the string to all lower-case except the first character which is
383 public static String toSentenceCase(String s)
391 return s.toUpperCase(Locale.ROOT);
393 return s.substring(0, 1).toUpperCase(Locale.ROOT) + s.substring(1).toLowerCase(Locale.ROOT);
397 * A helper method that strips off any leading or trailing html and body tags.
398 * If no html tag is found, then also html-encodes angle bracket characters.
403 public static String stripHtmlTags(String text)
409 String tmp2up = text.toUpperCase(Locale.ROOT);
410 int startTag = tmp2up.indexOf("<HTML>");
413 text = text.substring(startTag + 6);
414 tmp2up = tmp2up.substring(startTag + 6);
416 // is omission of "<BODY>" intentional here??
417 int endTag = tmp2up.indexOf("</BODY>");
420 text = text.substring(0, endTag);
421 tmp2up = tmp2up.substring(0, endTag);
423 endTag = tmp2up.indexOf("</HTML>");
426 text = text.substring(0, endTag);
429 if (startTag == -1 && (text.contains("<") || text.contains(">")))
431 text = text.replaceAll("<", "<");
432 text = text.replaceAll(">", ">");
438 * Answers the input string with any occurrences of the 'encodeable' characters
439 * replaced by their URL encoding
445 public static String urlEncode(String s, String encodable)
447 if (s == null || s.isEmpty())
453 * do % encoding first, as otherwise it may double-encode!
455 if (encodable.indexOf(PERCENT) != -1)
457 s = urlEncode(s, PERCENT);
460 for (char c : encodable.toCharArray())
471 * Answers the input string with any occurrences of {@code c} replaced with
472 * their url encoding. Answers the input string if it is unchanged.
478 static String urlEncode(String s, char c)
480 String decoded = String.valueOf(c);
481 if (s.indexOf(decoded) != -1)
483 String encoded = getUrlEncoding(c);
484 if (!encoded.equals(decoded))
486 s = s.replace(decoded, encoded);
493 * Answers the input string with any occurrences of the specified (unencoded)
494 * characters replaced by their URL decoding.
496 * Example: {@code urlDecode("a%3Db%3Bc", "-;=,")} should answer
503 public static String urlDecode(String s, String encodable)
505 if (s == null || s.isEmpty())
510 for (char c : encodable.toCharArray())
512 String encoded = getUrlEncoding(c);
513 if (s.indexOf(encoded) != -1)
515 String decoded = String.valueOf(c);
516 s = s.replace(encoded, decoded);
523 * Does a lazy lookup of the url encoding of the given character, saving the
524 * value for repeat lookups
529 private static String getUrlEncoding(char c)
531 if (c < 0 || c >= urlEncodings.length)
533 return String.valueOf(c);
536 String enc = urlEncodings[c];
541 enc = urlEncodings[c] = URLEncoder.encode(String.valueOf(c),
543 } catch (UnsupportedEncodingException e)
545 enc = urlEncodings[c] = String.valueOf(c);
552 * Answers true if the string is not empty and consists only of digits, or
553 * characters 'a'-'f' or 'A'-'F', else false
558 public static boolean isHexString(String s)
565 for (int i = 0; i < j; i++)
568 if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'))