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.ArrayList;
24 import java.util.List;
25 import java.util.regex.Pattern;
27 public class StringUtils
29 private static final Pattern DELIMITERS_PATTERN = Pattern
30 .compile(".*='[^']*(?!')");
32 private static final boolean DEBUG = false;
35 * Returns a new character array, after inserting characters into the given
39 * the character array to insert into
41 * the 0-based position for insertion
43 * the number of characters to insert
45 * the character to insert
47 public static final char[] insertCharAt(char[] in, int position,
50 char[] tmp = new char[in.length + count];
52 if (position >= in.length)
54 System.arraycopy(in, 0, tmp, 0, in.length);
59 System.arraycopy(in, 0, tmp, 0, position);
69 if (position < in.length)
71 System.arraycopy(in, position, tmp, index, in.length - position);
85 public static final char[] deleteChars(char[] in, int from, int to)
87 if (from >= in.length || from < 0)
97 System.arraycopy(in, 0, tmp, 0, from);
102 tmp = new char[in.length - to + from];
103 System.arraycopy(in, 0, tmp, 0, from);
104 System.arraycopy(in, to, tmp, from, in.length - to);
110 * Returns the last part of 'input' after the last occurrence of 'token'. For
111 * example to extract only the filename from a full path or URL.
115 * a delimiter which must be in regular expression format
118 public static String getLastToken(String input, String token)
128 String[] st = input.split(token);
129 return st[st.length - 1];
133 * Parses the input string into components separated by the delimiter. Unlike
134 * String.split(), this method will ignore occurrences of the delimiter which
135 * are nested within single quotes in name-value pair values, e.g. a='b,c'.
139 * @return elements separated by separator
141 public static String[] separatorListToArray(String input,
144 int seplen = delimiter.length();
145 if (input == null || input.equals("") || input.equals(delimiter))
149 List<String> jv = new ArrayList<String>();
150 int cp = 0, pos, escape;
151 boolean wasescaped = false, wasquoted = false;
152 String lstitem = null;
153 while ((pos = input.indexOf(delimiter, cp)) >= cp)
155 escape = (pos > 0 && input.charAt(pos - 1) == '\\') ? -1 : 0;
156 if (wasescaped || wasquoted)
158 // append to previous pos
159 jv.set(jv.size() - 1, lstitem = lstitem + delimiter
160 + input.substring(cp, pos + escape));
164 jv.add(lstitem = input.substring(cp, pos + escape));
167 wasescaped = escape == -1;
168 // last separator may be in an unmatched quote
169 wasquoted = DELIMITERS_PATTERN.matcher(lstitem).matches();
171 if (cp < input.length())
173 String c = input.substring(cp);
174 if (wasescaped || wasquoted)
176 // append final separator
177 jv.set(jv.size() - 1, lstitem + delimiter + c);
181 if (!c.equals(delimiter))
189 String[] v = jv.toArray(new String[jv.size()]);
193 System.err.println("Array from '" + delimiter
194 + "' separated List:\n" + v.length);
195 for (int i = 0; i < v.length; i++)
197 System.err.println("item " + i + " '" + v[i] + "'");
205 "Empty Array from '" + delimiter + "' separated List");
211 * Returns a string which contains the list elements delimited by the
212 * separator. Null items are ignored. If the input is null or has length zero,
213 * a single delimiter is returned.
217 * @return concatenated string
219 public static String arrayToSeparatorList(String[] list, String separator)
221 StringBuffer v = new StringBuffer();
222 if (list != null && list.length > 0)
224 for (int i = 0, iSize = list.length; i < iSize; i++)
232 // TODO - escape any separator values in list[i]
239 .println("Returning '" + separator + "' separated List:\n");
240 System.err.println(v);
247 "Returning empty '" + separator + "' separated List\n");
249 return "" + separator;
253 * Converts a list to a string with a delimiter before each term except the
254 * first. Returns an empty string given a null or zero-length argument. This
255 * can be replaced with StringJoiner in Java 8.
261 public static String listToDelimitedString(List<String> terms,
264 StringBuilder sb = new StringBuilder(32);
265 if (terms != null && !terms.isEmpty())
267 boolean appended = false;
268 for (String term : terms)
278 return sb.toString();
282 * Convenience method to parse a string to an integer, returning 0 if the
283 * input is null or not a valid integer
288 public static int parseInt(String s)
291 if (s != null && s.length() > 0)
295 result = Integer.parseInt(s);
296 } catch (NumberFormatException ex)
304 * Compares two versions formatted as e.g. "3.4.5" and returns -1, 0 or 1 as
305 * the first version precedes, is equal to, or follows the second
311 public static int compareVersions(String v1, String v2)
313 return compareVersions(v1, v2, null);
317 * Compares two versions formatted as e.g. "3.4.5b1" and returns -1, 0 or 1 as
318 * the first version precedes, is equal to, or follows the second
322 * @param pointSeparator
323 * a string used to delimit point increments in sub-tokens of the
327 public static int compareVersions(String v1, String v2,
328 String pointSeparator)
330 if (v1 == null || v2 == null)
334 String[] toks1 = v1.split("\\.");
335 String[] toks2 = v2.split("\\.");
337 for (; i < toks1.length; i++)
339 if (i >= toks2.length)
346 String tok1 = toks1[i];
347 String tok2 = toks2[i];
348 if (pointSeparator != null)
351 * convert e.g. 5b2 into decimal 5.2 for comparison purposes
353 tok1 = tok1.replace(pointSeparator, ".");
354 tok2 = tok2.replace(pointSeparator, ".");
358 float f1 = Float.valueOf(tok1);
359 float f2 = Float.valueOf(tok2);
360 int comp = Float.compare(f1, f2);
365 } catch (NumberFormatException e)
368 .println("Invalid version format found: " + e.getMessage());
373 if (i < toks2.length)
382 * same length, all tokens match
388 * Converts the string to all lower-case except the first character which is
394 public static String toSentenceCase(String s)
402 return s.toUpperCase();
404 return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
408 * A helper method that strips off any leading or trailing html and body tags.
409 * If no html tag is found, then also html-encodes angle bracket characters.
414 public static String stripHtmlTags(String text)
420 String tmp2up = text.toUpperCase();
421 int startTag = tmp2up.indexOf("<HTML>");
424 text = text.substring(startTag + 6);
425 tmp2up = tmp2up.substring(startTag + 6);
427 // is omission of "<BODY>" intentional here??
428 int endTag = tmp2up.indexOf("</BODY>");
431 text = text.substring(0, endTag);
432 tmp2up = tmp2up.substring(0, endTag);
434 endTag = tmp2up.indexOf("</HTML>");
437 text = text.substring(0, endTag);
440 if (startTag == -1 && (text.contains("<") || text.contains(">")))
442 text = text.replaceAll("<", "<");
443 text = text.replaceAll(">", ">");