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 * Parses the input string into components separated by the delimiter. Unlike
121 * String.split(), this method will ignore occurrences of the delimiter which
122 * are nested within single quotes in name-value pair values, e.g. a='b,c'.
126 * @return elements separated by separator
128 public static String[] separatorListToArray(String input,
131 int seplen = delimiter.length();
132 if (input == null || input.equals("") || input.equals(delimiter))
136 List<String> jv = new ArrayList<>();
137 int cp = 0, pos, escape;
138 boolean wasescaped = false, wasquoted = false;
139 String lstitem = null;
140 while ((pos = input.indexOf(delimiter, cp)) >= cp)
142 escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
143 if (wasescaped || wasquoted)
145 // append to previous pos
146 jv.set(jv.size() - 1, lstitem = lstitem + delimiter
147 + input.substring(cp, pos + escape));
151 jv.add(lstitem = input.substring(cp, pos + escape));
154 wasescaped = escape == -1;
155 // last separator may be in an unmatched quote
156 wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
158 if (cp < input.length())
160 String c = input.substring(cp);
161 if (wasescaped || wasquoted)
163 // append final separator
164 jv.set(jv.size() - 1, lstitem + delimiter + c);
168 if (!c.equals(delimiter))
176 String[] v = jv.toArray(new String[jv.size()]);
180 System.err.println("Array from '" + delimiter
181 + "' separated List:\n" + v.length);
182 for (int i = 0; i < v.length; i++)
184 System.err.println("item " + i + " '" + v[i] + "'");
192 "Empty Array from '" + delimiter + "' separated List");
198 * Returns a string which contains the list elements delimited by the
199 * separator. Null items are ignored. If the input is null or has length zero,
200 * a single delimiter is returned.
204 * @return concatenated string
206 public static String arrayToSeparatorList(String[] list, String separator)
208 StringBuffer v = new StringBuffer();
209 if (list != null && list.length > 0)
211 for (int i = 0, iSize = list.length; i < iSize; i++)
219 // TODO - escape any separator values in list[i]
226 .println("Returning '" + separator + "' separated List:\n");
227 System.err.println(v);
234 "Returning empty '" + separator + "' separated List\n");
236 return "" + separator;
240 * Converts a list to a string with a delimiter before each term except the
241 * first. Returns an empty string given a null or zero-length argument. This
242 * can be replaced with StringJoiner in Java 8.
248 public static String listToDelimitedString(List<String> terms,
251 StringBuilder sb = new StringBuilder(32);
252 if (terms != null && !terms.isEmpty())
254 boolean appended = false;
255 for (String term : terms)
265 return sb.toString();
269 * Convenience method to parse a string to an integer, returning 0 if the
270 * input is null or not a valid integer
275 public static int parseInt(String s)
278 if (s != null && s.length() > 0)
282 result = Integer.parseInt(s);
283 } catch (NumberFormatException ex)
291 * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
292 * the first version precedes, is equal to, or follows the second
298 public static int compareVersions(String v1, String v2)
300 return compareVersions(v1, v2, null);
304 * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
305 * the first version precedes, is equal to, or follows the second
309 * @param pointSeparator
310 * a string used to delimit point increments in sub-tokens of the
314 public static int compareVersions(String v1, String v2,
315 String pointSeparator)
317 if (v1 == null || v2 == null)
321 String[] toks1 = v1.split("\\.");
322 String[] toks2 = v2.split("\\.");
324 for (; i < toks1.length; i++)
326 if (i >= toks2.length)
333 String tok1 = toks1[i];
334 String tok2 = toks2[i];
335 if (pointSeparator != null)
338 * convert e.g. 5b2 into decimal 5.2 for comparison purposes
340 tok1 = tok1.replace(pointSeparator, ".");
341 tok2 = tok2.replace(pointSeparator, ".");
345 float f1 = Float.valueOf(tok1);
346 float f2 = Float.valueOf(tok2);
347 int comp = Float.compare(f1, f2);
352 } catch (NumberFormatException e)
355 .println("Invalid version format found: " + e.getMessage());
360 if (i < toks2.length)
369 * same length, all tokens match
375 * Converts the string to all lower-case except the first character which is
381 public static String toSentenceCase(String s)
389 return s.toUpperCase();
391 return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
395 * A helper method that strips off any leading or trailing html and body tags.
396 * If no html tag is found, then also html-encodes angle bracket characters.
401 public static String stripHtmlTags(String text)
407 String tmp2up = text.toUpperCase();
408 int startTag = tmp2up.indexOf("<HTML>");
411 text = text.substring(startTag + 6);
412 tmp2up = tmp2up.substring(startTag + 6);
414 // is omission of "<BODY>" intentional here??
415 int endTag = tmp2up.indexOf("</BODY>");
418 text = text.substring(0, endTag);
419 tmp2up = tmp2up.substring(0, endTag);
421 endTag = tmp2up.indexOf("</HTML>");
424 text = text.substring(0, endTag);
427 if (startTag == -1 && (text.contains("<") || text.contains(">")))
429 text = text.replaceAll("<", "<");
430 text = text.replaceAll(">", ">");
436 * Answers the input string with any occurrences of the 'encodeable' characters
437 * replaced by their URL encoding
443 public static String urlEncode(String s, String encodable)
445 if (s == null || s.isEmpty())
451 * do % encoding first, as otherwise it may double-encode!
453 if (encodable.indexOf(PERCENT) != -1)
455 s = urlEncode(s, PERCENT);
458 for (char c : encodable.toCharArray())
469 * Answers the input string with any occurrences of {@code c} replaced with
470 * their url encoding. Answers the input string if it is unchanged.
476 static String urlEncode(String s, char c)
478 String decoded = String.valueOf(c);
479 if (s.indexOf(decoded) != -1)
481 String encoded = getUrlEncoding(c);
482 if (!encoded.equals(decoded))
484 s = s.replace(decoded, encoded);
491 * Answers the input string with any occurrences of the specified (unencoded)
492 * characters replaced by their URL decoding.
494 * Example: {@code urlDecode("a%3Db%3Bc", "-;=,")} should answer
501 public static String urlDecode(String s, String encodable)
503 if (s == null || s.isEmpty())
508 for (char c : encodable.toCharArray())
510 String encoded = getUrlEncoding(c);
511 if (s.indexOf(encoded) != -1)
513 String decoded = String.valueOf(c);
514 s = s.replace(encoded, decoded);
521 * Does a lazy lookup of the url encoding of the given character, saving the
522 * value for repeat lookups
527 private static String getUrlEncoding(char c)
529 if (c < 0 || c >= urlEncodings.length)
531 return String.valueOf(c);
534 String enc = urlEncodings[c];
539 enc = urlEncodings[c] = URLEncoder.encode(String.valueOf(c),
541 } catch (UnsupportedEncodingException e)
543 enc = urlEncodings[c] = String.valueOf(c);
550 * Answers true if the string is not empty and consists only of digits, or
551 * characters 'a'-'f' or 'A'-'F', else false
556 public static boolean isHexString(String s)
563 for (int i = 0; i < j; i++)
566 if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'))