JAL-845 further code/tests/refactoring
[jalview.git] / src / jalview / util / StringUtils.java
1 package jalview.util;
2
3
4 public class StringUtils
5 {
6
7   /**
8    * Returns a new character array, after inserting characters into the given
9    * character array.
10    * 
11    * @param in
12    *          the character array to insert into
13    * @param position
14    *          the 0-based position for insertion
15    * @param count
16    *          the number of characters to insert
17    * @param ch
18    *          the character to insert
19    */
20   public static final char[] insertCharAt(char[] in, int position,
21           int count,
22           char ch)
23   {
24     char[] tmp = new char[in.length + count];
25   
26     if (position >= in.length)
27     {
28       System.arraycopy(in, 0, tmp, 0, in.length);
29       position = in.length;
30     }
31     else
32     {
33       System.arraycopy(in, 0, tmp, 0, position);
34     }
35   
36     int index = position;
37     while (count > 0)
38     {
39       tmp[index++] = ch;
40       count--;
41     }
42   
43     if (position < in.length)
44     {
45       System.arraycopy(in, position, tmp, index,
46               in.length - position);
47     }
48   
49     return tmp;
50   }
51
52   /**
53    * Delete
54    * 
55    * @param in
56    * @param from
57    * @param to
58    * @return
59    */
60   public static final char[] deleteChars(char[] in, int from, int to)
61   {
62     if (from >= in.length)
63     {
64       return in;
65     }
66
67     char[] tmp;
68
69     if (to >= in.length)
70     {
71       tmp = new char[from];
72       System.arraycopy(in, 0, tmp, 0, from);
73       to = in.length;
74     }
75     else
76     {
77       tmp = new char[in.length - to + from];
78       System.arraycopy(in, 0, tmp, 0, from);
79       System.arraycopy(in, to, tmp, from, in.length - to);
80     }
81     return tmp;
82   }
83
84   /**
85    * Returns the last part of 'input' after the last occurrence of 'token'. For
86    * example to extract only the filename from a full path or URL.
87    * 
88    * @param input
89    * @param token
90    *          a delimiter which must be in regular expression format
91    * @return
92    */
93   public static String getLastToken(String input, String token)
94   {
95     if (input == null)
96     {
97       return null;
98     }
99     if (token == null)
100     {
101       return input;
102     }
103     String[] st = input.split(token);
104     return st[st.length - 1];
105   }
106 }