View Javadoc

1   package com.sri.emo.wizard.creation;
2   
3   /***
4    * @author Richard Vorp
5    * @version 1.0
6    */
7   import java.text.*;
8   import java.util.*;
9   
10  /***
11   * Created by Richard Vorp to include all of the
12   * utility function which deal with string manipulation
13   * or string creation
14   */
15  public class StringUtil {
16    public static final int LEFT_ALIGN = 0;
17    public static final int CENTER_ALIGN = 1;
18    public static final int RIGHT_ALIGN = 2;
19    public static NumberFormat nf = NumberFormat.getInstance();
20    //no one should create a string utility object
21    private StringUtil() {}
22  
23    /***
24     * Finds the first index of any character (represented by searchCharacter)
25     * within the string.
26     * returns -1 if no character is found
27     * @param string String
28     * @param searchCharacters String
29     * @return int
30     */
31    public static int indexOf(String string, String searchCharacters){
32      for(int i = 0; i < string.length(); i++){
33        if(searchCharacters.indexOf(string.charAt(i)) != -1){
34          return i;
35        }
36      }
37      return -1;
38    }
39  
40    public static String toString(Map map) {
41      String s="";
42      for (Iterator iter = map.keySet().iterator(); iter.hasNext(); ) {
43        Object key = (Object)iter.next();
44        s+=key + " --> "+ map.get(key)+"\n";
45      }
46      return s;
47     }
48  
49     public static String getIth(int number){
50       switch(number%10){
51         case 1:
52           return number+"st";
53         case 2:
54           return number+"nd";
55         case 3:
56           return number+"rd";
57         default:
58           return number+"th";
59       }
60     }
61  
62    public static String toString(String[] strArray) {
63      StringBuffer buffer = new StringBuffer();
64      buffer.append("[ ");
65      buffer.append(strArray[0]);
66      for (int i = 1; i < strArray.length; i++) {
67        buffer.append(" , ");
68       buffer.append(strArray[i]);
69      }
70      buffer.append(" ] ");
71      return buffer.toString();
72    }
73  
74    public static String toString(Collection c) {
75      return toString(c, "[", "]");
76    }
77  
78    public static String toString(Collection c, String start, String end) {
79      return toString(c, start, " , ", end);
80    }
81  
82    public static String toString(Collection c, String start, String separator,
83                                  String end) {
84      if (c == null) {
85        return "null";
86      }
87      return toString(c.iterator(), start, separator, end);
88    }
89  
90    public static String toString(Enumeration enumeration){
91      return toString(enumeration, "[", ",", "]");
92    }
93  
94    public static String toString(Enumeration iterator, String start, String separator,
95                                  String end){
96      StringBuffer buffer = new StringBuffer();
97      buffer.append(start);
98      while (iterator.hasMoreElements()) {
99        Object next = iterator.nextElement();
100       buffer.append(next == null ? "null" : next.toString());
101       if (iterator.hasMoreElements()) {
102         buffer.append(separator);
103       }
104     }
105     buffer.append(end);
106     return buffer.toString();
107 
108   }
109 
110 
111   public static String toString(Iterator iterator){
112     return toString(iterator, "[", ",", "]");
113   }
114 
115   public static String toString(Iterator iterator, String start, String separator,
116                                 String end){
117     StringBuffer buffer = new StringBuffer();
118     buffer.append(start);
119     while (iterator.hasNext()) {
120       Object next = iterator.next();
121       buffer.append(next == null ? "null" : next.toString());
122       if (iterator.hasNext()) {
123         buffer.append(separator);
124       }
125     }
126     buffer.append(end);
127     return buffer.toString();
128 
129   }
130 
131   public static String toString(Object[] values){
132     return toString(values, "[", "][", "]");
133   }
134 
135   public static String toStringLn(Object[] values){
136     return toString(values, "[", "]\n[", "]");
137   }
138 
139   public static String toString(Object[] values, String start, String separator,
140                                 String end) {
141     StringBuffer buffer = new StringBuffer();
142     buffer = oneDimensionBuffer(buffer, values, start, separator, end);
143     return buffer.toString();
144   }
145 
146   private static StringBuffer oneDimensionBuffer(StringBuffer buffer,
147                                                  Object[] values, String start,
148                                                  String separator, String end) {
149     buffer.append(start);
150     for (int i = 0; i < values.length; i++) {
151       if(values[i] == null){
152         throw new NullPointerException("value at index " + i + " is null");
153       }
154       buffer.append(values[i].toString());
155       if (i < values.length - 1) {
156         buffer.append(separator);
157       }
158     }
159     buffer.append(end);
160     return buffer;
161   }
162 
163 
164   public static String toString(int[] values) {
165     return toString(values, "[", "][", "]");
166   }
167 
168   public static String toString(int[] values, String start, String separator,
169                                 String end) {
170     StringBuffer buffer = new StringBuffer();
171     buffer = oneDimensionBuffer(buffer, values, start, separator, end);
172     return buffer.toString();
173   }
174 
175   public static String toString(int[][] values) {
176     return toString(values, "[", "][", "]\n", "[", "][", "]");
177   }
178 
179   public static String toString(int[][] values, String firstDimStart,
180                                 String firstDimSeparator,
181                                 String firstDimEnd, String secondDimStart,
182                                 String secondDimSeparator, String secondDimEnd) {
183     StringBuffer buffer = new StringBuffer();
184     buffer.append(firstDimStart);
185     for (int i = 0; i < values.length; i++) {
186       buffer = oneDimensionBuffer(buffer, values[i], secondDimStart,
187                                   secondDimSeparator, secondDimEnd);
188       if (i < values.length - 1) {
189         buffer.append(firstDimSeparator);
190       }
191     }
192     buffer.append(firstDimEnd);
193     return buffer.toString();
194   }
195 
196   private static StringBuffer oneDimensionBuffer(StringBuffer buffer,
197                                                  int[] values, String start,
198                                                  String separator, String end) {
199     buffer.append(start);
200     for (int i = 0; i < values.length; i++) {
201       buffer.append(values[i]);
202       if (i < values.length - 1) {
203         buffer.append(separator);
204       }
205     }
206     buffer.append(end);
207     return buffer;
208   }
209 
210   private static StringBuffer oneDimensionBuffer(StringBuffer buffer,
211                                                  double[] values, String start,
212                                                  String separator, String end) {
213     buffer.append(start);
214     for (int i = 0; i < values.length; i++) {
215       if(values[i] >= 0){
216         buffer.append(" ");
217       }
218       buffer.append(values[i]);
219       if (i < values.length - 1) {
220         buffer.append(separator);
221       }
222     }
223     buffer.append(end);
224     return buffer;
225   }
226 
227   private static StringBuffer oneDimensionBuffer(StringBuffer buffer,
228                                                  boolean[] values, String start,
229                                                  String separator, String end) {
230     buffer.append(start);
231     for (int i = 0; i < values.length; i++) {
232       buffer.append(values[i]);
233       if (i < values.length - 1) {
234         buffer.append(separator);
235       }
236     }
237     buffer.append(end);
238     return buffer;
239   }
240 
241 
242   public static String toString(double[] values, String start, String separator,
243                                 String end) {
244     StringBuffer buffer = new StringBuffer();
245     buffer = oneDimensionBuffer(buffer, values, start, separator, end);
246     return buffer.toString();
247   }
248 
249   public static String toString(boolean[] values, String start, String separator,
250                                 String end) {
251     StringBuffer buffer = new StringBuffer();
252     buffer = oneDimensionBuffer(buffer, values, start, separator, end);
253     return buffer.toString();
254   }
255 
256 
257   public static String toString(double[] values) {
258     return toString(values, "[", "][", "]");
259   }
260 
261   public static String toString(boolean[] values) {
262     return toString(values, "[", "][", "]");
263   }
264 
265   public static String toString(double[][][] values, String firstDimStart,
266                                 String firstDimEnd, String firstDimSeparator,
267                                 String secondDimStart,
268                                 String secondDimSeparator,
269                                 String secondDimEnd, String thirdDimStart,
270                                 String thirdDimSeparator, String thirdDimEnd) {
271     StringBuffer buffer = new StringBuffer();
272     buffer.append(firstDimStart);
273     for (int i = 0; i < values.length; i++) {
274       buffer.append(secondDimStart);
275       for (int j = 0; j < values[i].length; j++) {
276         buffer = oneDimensionBuffer(buffer, values[i][j], thirdDimStart,
277                                     thirdDimSeparator, thirdDimEnd);
278         if (j < values[i].length - 1) {
279           buffer.append(secondDimSeparator);
280         }
281       }
282       buffer.append(secondDimEnd);
283       if (i < values.length - 1) {
284         buffer.append(firstDimSeparator);
285       }
286     }
287     buffer.append(firstDimEnd);
288     return buffer.toString();
289   }
290 
291   public static String toString(double[][][] values) {
292     return toString(values, "{", "}{", "}\n", "[", "][", "]\n", "[", "][", "]");
293   }
294 
295   public static String toString(double[][] values, String firstDimStart,
296                                 String firstDimSeparator,
297                                 String firstDimEnd, String secondDimStart,
298                                 String secondDimSeparator, String secondDimEnd) {
299     StringBuffer buffer = new StringBuffer();
300     buffer.append(firstDimStart);
301     for (int i = 0; i < values.length; i++) {
302       buffer = oneDimensionBuffer(buffer, values[i], secondDimStart,
303                                   secondDimSeparator, secondDimEnd);
304       if (i < values.length - 1) {
305         buffer.append(firstDimSeparator);
306       }
307     }
308     buffer.append(firstDimEnd);
309     return buffer.toString();
310   }
311 
312   public static String toString(double[][] values) {
313     return toString(values, "[", "]\n[", "]\n", "[", "][", "]");
314   }
315 
316   public static String toString(boolean[][] values) {
317     return toString(values, "[", "][", "]\n", "[", "]\n[", "]");
318   }
319 
320 
321   public static String toString(boolean[][] values, String firstDimStart,
322                                 String firstDimSeparator,
323                                 String firstDimEnd, String secondDimStart,
324                                 String secondDimSeparator, String secondDimEnd) {
325     StringBuffer buffer = new StringBuffer();
326     buffer.append(firstDimStart);
327     for (int i = 0; i < values.length; i++) {
328       buffer = oneDimensionBuffer(buffer, values[i], secondDimStart,
329                                   secondDimSeparator, secondDimEnd);
330       if (i < values.length - 1) {
331         buffer.append(firstDimSeparator);
332       }
333     }
334     buffer.append(firstDimEnd);
335     return buffer.toString();
336   }
337 
338 
339   /***
340    * tests to see whether the child string is contained within the parent
341    * @param parent
342    * @param child
343    * @return
344    */
345   public static boolean contains(String parent, String child) {
346     int childIndex = 0;
347     for (int i = 0; i < parent.length() && childIndex < child.length(); i++) {
348       if (parent.charAt(i) == child.charAt(childIndex)) {
349         childIndex++;
350       }
351       else {
352         childIndex = 0;
353       }
354     }
355     if (childIndex >= child.length()) {
356       return true;
357     }
358     return false;
359   }
360 
361   public static int countNonEmptyStrings(String[] text){
362     int count = 0;
363     for(int i = 0; i < text.length; i++){
364       if(text[i].length() > 0){
365         count++;
366       }
367     }
368     return count;
369   }
370 
371   /***
372    * @return A string which represents a character duplicated n times
373    */
374   public static String createString(char val, int width) {
375     if (width < 0) {
376       return "";
377     }
378     StringBuffer b = new StringBuffer(width);
379     for (int i = 0; i < width; i++) {
380       b.append(val);
381     }
382     return b.toString();
383   }
384 
385   /***
386    * Creates a string with VAL repeated WIDTH times in a line
387    * and height many lines. It ends with a newline character.
388    * @param val
389    * @param width
390    * @param height
391    * @return a string with VAL repeated WIDTH times in a line
392    * and height many lines
393    */
394   public static String createString(String val, int width, int height) {
395     String s = "";
396     for (int i = 0; i < height; i++) {
397       s = s + createString(val, width) +
398           System.getProperty("line.separator");
399     }
400     return s;
401   }
402 
403   public static String createString(String val, int width) {
404     StringBuffer b = new StringBuffer();
405     for (int i = 0; i < width; i++) {
406       b.append(val);
407     }
408     return b.toString();
409   }
410 
411   public static String space(int times) {
412     return createString(' ', times);
413   }
414 
415   /***
416    * inserts a String txt into a buffer of size length.
417    * if the String is too large, it will be truncated to size length.
418    * Otherwise it uses the aligment to determine how to align the txt
419    * within the buffer.
420    * Valid alignments are LEFT_ALIGN, CENTER_ALIGN, and RIGHT_ALIGN
421    * if an invalid alignment is given, LEFT_ALIGN is assumed.
422    * @param txt String to fit in a buffer
423    * @param length
424    * @param alignment
425    * @return
426    */
427   public static String buffer(String txt, int length, int alignment) {
428     switch (alignment) {
429       case RIGHT_ALIGN:
430         return bufferRightAlign(txt, length);
431       case CENTER_ALIGN:
432         return bufferCenterAlign(txt, length);
433       default:
434         return buffer(txt, length);
435     }
436   }
437 
438   public static List wrapLines(String text, int maxLength){
439     List lines = new Vector(10);
440     StringTokenizer tokenizer = new StringTokenizer(text, " ");
441     StringBuffer buffer = new StringBuffer();
442     int currentLength = 0;
443     int proposedLength = 0;
444     while(tokenizer.hasMoreTokens()){
445       String word = tokenizer.nextToken();
446       proposedLength += word.length();
447       if(proposedLength > maxLength && currentLength > 0){
448         lines.add(buffer.toString());
449         buffer.delete(0, buffer.length());
450         proposedLength = 0;
451       }else{
452         proposedLength++;
453         currentLength = proposedLength;
454         buffer.append(" ");
455       }
456       buffer.append(word);
457     }
458     if(buffer.length() > 0){
459       lines.add(buffer.toString());
460     }
461     System.out.println("wrapped = " + buffer.toString());
462     return lines;
463   }
464 
465   public static String wrap(String text, int maxLength){
466     StringTokenizer tokenizer = new StringTokenizer(text, " ");
467     StringBuffer buffer = new StringBuffer();
468     int currentLength = 0;
469     int proposedLength = 0;
470     while(tokenizer.hasMoreTokens()){
471       String word = tokenizer.nextToken();
472       proposedLength += word.length();
473       if(proposedLength > maxLength && currentLength > 0){
474         buffer.append("\n");
475         proposedLength = 0;
476       }else{
477         proposedLength++;
478         currentLength = proposedLength;
479         buffer.append(" ");
480       }
481       buffer.append(word);
482     }
483     System.out.println("wrapped = " + buffer.toString());
484     return buffer.toString();
485   }
486 
487   /***
488    * inserts a String txt into a buffer of size length.
489    * if the String is too small, the returned string will have
490    * trailing whitespace characters after it. If the string is too
491    * big the extra characters will be cut off.
492    * @param txt
493    * @param length
494    * @return String of size length with txt in it.
495    */
496   public static String buffer(String txt, int length) {
497     if (txt.length() >= length) {
498       return txt.substring(0, length);
499     }
500     else {
501       return txt + createString(' ', length - txt.length());
502     }
503   }
504 
505   /***
506    * inserts a String txt into a buffer of size length.
507    * if the String is too small, the returned string will have
508    * trailing whitespace characters after it. If the string is too
509    * big nothing is done to shorten it.  In other words, the new returned
510    * String will be exactly what was passed in.
511    * @param txt
512    * @param length
513    * @return String of size length with txt in it.
514    */
515   public static String bufferNoTrim(String txt, int length) {
516     if (txt.length() >= length) {
517       return txt;
518     }
519     else {
520       return txt + createString(' ', length - txt.length());
521     }
522   }
523 
524   /***
525    * inserts a String txt into a buffer of size length.
526    * if the String is too small, the returned string will have
527    * trailing whitespace characters before it.
528    * @return String of size length with txt in it.
529    */
530   public static String bufferRightAlign(String txt, int length) {
531     return bufferRightAlign(txt, " ", length);
532   }
533 
534   public static String bufferRightAlign(String txt, String bufferTxt, int length){
535     if (txt.length() >= length) {
536       return txt.substring(0, length);
537     }
538     else {
539       return createString(bufferTxt, length - txt.length()) + txt;
540     }
541   }
542 
543   /***
544    * inserts a double value into a buffer of size length.
545    * the value is formated according to the NumberFormat passed into it.
546    * If the value is positive a leading space is entered before it, to account
547    * for the negative values taking up that space with a - sign
548    * if the value is too small, the returned string will have
549    * trailing whitespace characters after it.
550    * @return String of size length with value in it.
551    */
552   public static String buffer(java.text.NumberFormat nf, double value,
553                               int length) {
554     String str;
555     if (value >= 0) {
556       str = " ";
557       str += StringUtil.buffer(nf.format(value), length - 1);
558     }
559     else {
560       str = StringUtil.buffer(nf.format(value), length);
561     }
562     return str;
563   }
564 
565   /***
566    * inserts a String txt into a buffer of size length.
567    * if the String is too small, the returned string will have
568    * trailing whitespace characters before and after it.
569    * @return String of size length with txt centered in it.
570    */
571   public static String bufferCenterAlign(String txt, int length) {
572     if (txt.length() >= length) {
573       return txt.substring(0, length);
574     }
575     else {
576       String s = createString(' ', (length - txt.length()) / 2);
577       s = s + txt + s;
578       if (s.length() < length) {
579         s += " ";
580       }
581       return s;
582     }
583   }
584 
585   /***
586    * Makes a right aligned string buffer out of double. Useful for
587    * fractional numbers.
588    * @param value double value to be made into string
589    * @param numFracDigits number digits after fraction dot.
590    * @return string that contains value right aligned.
591    */
592   public static String bufferRightAlign(double value, int numFracDigits,
593                                         int length) {
594     return bufferRightAlign(format(value, numFracDigits), length);
595   }
596 
597   public static String removeOuterChar(String s, char leftOuter, char rightOuter) {
598     s = s.trim();
599     StringBuffer buffer = new StringBuffer(s);
600     try {
601       if(buffer.length() > 0 && buffer.charAt(0) == leftOuter){
602         buffer.delete(0,1);
603       }
604       if(buffer.length() > 0 && buffer.charAt(buffer.length()-1) == rightOuter){
605         buffer.delete(buffer.length()-1, buffer.length());
606       }
607 //      System.out.println("returning buffer:["+buffer.toString()+"]");
608       return buffer.toString();
609     }
610        catch (StringIndexOutOfBoundsException e) {
611          System.out.println("ERROR : Invalid range of indexes");
612          return s;
613        }
614   }
615 
616 
617   public static String removeOuterChars(String s, char leftOuter, char rightOuter) {
618     s = s.trim();
619     StringBuffer buffer = new StringBuffer(s);
620     try {
621       while(buffer.length() > 0 && buffer.charAt(0) == leftOuter){
622         buffer.delete(0,1);
623       }
624       while(buffer.length() > 0 && buffer.charAt(buffer.length()-1) == rightOuter){
625         buffer.delete(buffer.length()-1, buffer.length());
626       }
627 //      System.out.println("returning buffer:["+buffer.toString()+"]");
628       return buffer.toString();
629     }
630        catch (StringIndexOutOfBoundsException e) {
631          System.out.println("ERROR : Invalid range of indexes");
632          return s;
633        }
634   }
635 
636   public static String trim(String line, char trimCharacter){
637 //    System.out.println("StringUtil.removeQuotesNoTrim("+s+")");
638     StringBuffer buffer = new StringBuffer(line);
639     try {
640       while(buffer.length() > 0 && buffer.charAt(0) == trimCharacter){
641         buffer.delete(0,1);
642       }
643       while(buffer.length() > 0 && buffer.charAt(buffer.length()-1) == trimCharacter){
644         buffer.delete(buffer.length()-1, buffer.length());
645       }
646 //      System.out.println("returning buffer:["+buffer.toString()+"]");
647       return buffer.toString();
648 //      if (line.startsWith("\"") && line.endsWith("\"")) {
649 //        return line.substring(1, line.length() - 1);
650 //      }
651     }
652     catch (StringIndexOutOfBoundsException e) {
653       System.out.println("ERROR : Invalid range of indexes");
654       return line;
655     }
656 //    return s;
657   }
658   /***
659    * @return a String with any quotes removed from it
660    */
661   public static String removeQuotesNoTrim(String s) {
662     return trim(s.trim(), '\"');
663   }
664 
665   /***
666    * @return a String with any quotes removed from it and also
667    * trimming it afterwards.
668    */
669   public static String removeQuotes(String s) {
670     return removeQuotesNoTrim(s).trim();
671   }
672 
673   public static String format(double value, int maxFracDigits) {
674     nf.setMaximumFractionDigits(maxFracDigits);
675     nf.setMinimumFractionDigits(maxFracDigits);
676     return nf.format(value);
677   }
678 
679   /***
680    * Determines he first longest from a list of strings
681    * @author Sevan Tutunciyan
682    * @param stringList
683    * @return the first occurence of longest string.
684    */
685   public static String longestString(List stringList) {
686     Iterator iter = stringList.iterator();
687     return longestString(iter);
688   }
689 
690   public static String longestString(Iterator iter) {
691     String longestString = "";
692     while (iter.hasNext()) {
693       String currString = (String) iter.next();
694       if (longestString.length() < currString.length()) {
695         longestString = currString;
696       }
697     }
698     return longestString;
699   }
700 
701   /***
702    * Determines he first longest from a array of strings
703    * @author Sevan Tutunciyan
704    * @param stringArray
705    * @return the first occurence of longest string.
706    */
707   public static String longestString(Object[] stringArray) {
708     String longestString = "";
709     for (int i = 0; i < stringArray.length; i++) {
710       String currString = (String) stringArray[i];
711       if (longestString.length() < currString.length()) {
712         longestString = currString;
713       }
714     }
715     return longestString;
716   }
717 
718   public static String getPlural(String text, int number){
719     if(number == 1){
720       return text;
721     }else{
722       return text+"s";
723     }
724   }
725   public static int[] parseIntegerTokens(String s, String delimit) {
726       StringTokenizer st= new StringTokenizer(s,delimit);
727       int[] intTokens=new int[st.countTokens()];
728       for (int i=0;st.hasMoreTokens();i++) {
729         intTokens[i]=Integer.parseInt(st.nextToken());
730       }
731       return intTokens;
732     }
733 
734   public static double[] parseDoubleTokens(String s, String delimit) {
735     StringTokenizer st= new StringTokenizer(s,delimit);
736     double[] doubleTokens=new double[st.countTokens()];
737     for (int i=0;st.hasMoreTokens();i++) {
738       doubleTokens[i]=Double.parseDouble(st.nextToken());
739     }
740     return doubleTokens;
741   }
742 
743 public static String appendIfNotExist(String originalString, String appendString){
744   if(originalString.endsWith(appendString)){
745     return originalString;
746   }else{
747     return originalString+appendString;
748   }
749 }
750 
751 
752 }