KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > prefuse > util > StringLib


1 package prefuse.util;
2
3 import java.awt.FontMetrics JavaDoc;
4 import java.io.IOException JavaDoc;
5 import java.io.PrintWriter JavaDoc;
6 import java.io.StreamTokenizer JavaDoc;
7 import java.io.StringReader JavaDoc;
8 import java.io.StringWriter JavaDoc;
9 import java.lang.reflect.Array JavaDoc;
10 import java.util.Hashtable JavaDoc;
11
12 /**
13  * Library of utility routines pertaining to Strings.
14  *
15  * @author <a HREF="http://jheer.org">jeffrey heer</a>
16  */

17 public class StringLib {
18
19     private StringLib() {
20         // prevent instantiation
21
}
22
23     /**
24      * Given an array object, create a String showing the contents
25      * of the array using a "[a[0], a[1], ..., a[a.length-1]]" format.
26      * @param a the array object
27      * @return the array string
28      */

29     public static final String JavaDoc getArrayString(Object JavaDoc a) {
30         StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
31         sbuf.append('[');
32         int size = Array.getLength(a);
33         for ( int i=0; i<size; ++i ) {
34             if ( i>0 ) sbuf.append(", ");
35             sbuf.append(Array.get(a, i));
36         }
37         sbuf.append(']');
38         return sbuf.toString();
39     }
40     
41     /**
42      * Format the given number as a String, including the given number of
43      * decimal places.
44      * @param number the number to format
45      * @param decimalPlaces the number of decimal places to include
46      * @return the formatted String
47      */

48     public static String JavaDoc formatNumber(double number, int decimalPlaces) {
49         String JavaDoc s = String.valueOf(number);
50         int idx1 = s.indexOf('.');
51         if ( idx1 == -1 ) {
52             return s;
53         } else {
54             int idx2 = s.indexOf('E');
55             int dp = decimalPlaces + (idx2>=0 ? 0 : 1);
56             String JavaDoc t = s.substring(0, Math.min(idx1+dp, s.length()));
57             if ( idx2 >= 0 )
58                 t += s.substring(idx2);
59             return t;
60         }
61     }
62     
63     /**
64      * Capitalize all letters preceded by whitespace, and lower case
65      * all other letters.
66      * @param s the String to capitalize
67      * @return the capitalized string
68      */

69     public static String JavaDoc capitalizeFirstOnly(String JavaDoc s) {
70         if ( s == null )
71             return null;
72         if ( s.length() == 0 )
73             return s;
74         
75         StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
76         char c = s.charAt(0);
77         sbuf.append(Character.toUpperCase(c));
78         boolean space = Character.isWhitespace(c);
79         for ( int i=1; i<s.length(); ++i ) {
80             c = s.charAt(i);
81             if ( Character.isWhitespace(c) ) {
82                 space = true;
83             } else if ( space ) {
84                 c = Character.toUpperCase(c);
85                 space = false;
86             } else {
87                 c = Character.toLowerCase(c);
88             }
89             sbuf.append(c);
90         }
91         return sbuf.toString();
92     }
93     
94     /**
95      * Get the stack trace of the given Throwable as a String.
96      * @param t the Throwable
97      * @return the stack trace of the Throwable
98      */

99     public static String JavaDoc getStackTrace(Throwable JavaDoc t) {
100         StringWriter JavaDoc sw = new StringWriter JavaDoc();
101         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
102         t.printStackTrace(pw);
103         pw.close();
104         return sw.toString();
105     }
106     
107     // ------------------------------------------------------------------------
108
// Abbreviation Methods
109

110     private static final String JavaDoc SUFFIX = "suffix";
111     private static final String JavaDoc PREFIX = "prefix";
112     private static Hashtable JavaDoc prefixSuffixT = new Hashtable JavaDoc();
113     static {
114         prefixSuffixT.put( "mr", PREFIX );
115         prefixSuffixT.put( "mr.", PREFIX );
116         prefixSuffixT.put( "dr", PREFIX );
117         prefixSuffixT.put( "dr.", PREFIX );
118         prefixSuffixT.put( "lt", PREFIX );
119         prefixSuffixT.put( "lt.", PREFIX );
120         prefixSuffixT.put( "gen", PREFIX );
121         prefixSuffixT.put( "gen.", PREFIX );
122         prefixSuffixT.put( "sgt", PREFIX );
123         prefixSuffixT.put( "sgt.", PREFIX );
124         prefixSuffixT.put( "cmdr", PREFIX );
125         prefixSuffixT.put( "cmdr.", PREFIX );
126         prefixSuffixT.put( "cpt", PREFIX );
127         prefixSuffixT.put( "cpt.", PREFIX );
128         prefixSuffixT.put( "ii", SUFFIX );
129         prefixSuffixT.put( "iii", SUFFIX );
130         prefixSuffixT.put( "iv", SUFFIX );
131         prefixSuffixT.put( "jr", SUFFIX );
132         prefixSuffixT.put( "jr.", SUFFIX );
133         prefixSuffixT.put( "sr", SUFFIX );
134         prefixSuffixT.put( "sr.", SUFFIX );
135     }
136     
137     /**
138      * Abbreviate a String by simply truncating it.
139      * @param str the String to abbreviate
140      * @param fm the FontMetrics for measuring the String length
141      * @param width the maximum string width, in pixels
142      * @return an abbreviated String
143      */

144     public static String JavaDoc abbreviate(String JavaDoc str, FontMetrics JavaDoc fm, int width) {
145         int lastblank = 0, nchars = 0, cumx = 0;
146         while ( cumx < width && nchars < str.length() ) {
147         if ( Character.isWhitespace(str.charAt(nchars)) ) {
148             lastblank = nchars;
149         }
150         cumx += fm.charWidth(str.charAt(nchars));
151         nchars++;
152         }
153         if ( nchars < str.length() && lastblank > 0 ) { nchars = lastblank; }
154         return ( nchars > 0 ? str.substring(0, nchars) : str );
155     }
156
157     /**
158      * Abbreviate a String as a given name.
159      * @param str the String to abbreviate
160      * @param fm the FontMetrics for measuring the String length
161      * @param width the maximum string width, in pixels
162      * @return an abbreviated String
163      */

164     public static String JavaDoc abbreviateName(String JavaDoc str, FontMetrics JavaDoc fm, int width)
165     {
166         if (fm.stringWidth(str) > width) str = abbreviateName(str, false);
167         if (fm.stringWidth(str) > width) str = abbreviateName(str, true);
168         return str;
169     }
170     
171     /**
172      * String abbreviation helper method for name strings.
173      * @param inString the String to abbreviate
174      * @param lastOnly true to include only the last name, false otherwise
175      * @return an abbreviated name
176      */

177     private static String JavaDoc abbreviateName(String JavaDoc inString, boolean lastOnly) {
178         StringReader JavaDoc in = new StringReader JavaDoc(inString);
179         StreamTokenizer JavaDoc p = new StreamTokenizer JavaDoc(in);
180         p.wordChars('&', '&');
181         p.wordChars('@', '@');
182         p.wordChars(':', ':');
183         p.ordinaryChar(',');
184         p.ordinaryChar('-');
185         int c;
186         String JavaDoc lastNameHold = null;
187         String JavaDoc lastInitialHold = null;
188         StringBuffer JavaDoc outString = new StringBuffer JavaDoc();
189         try {
190         out:
191             while (true) {
192             c = p.nextToken();
193             switch (c) {
194             case StreamTokenizer.TT_EOF:
195                 break out;
196             case StreamTokenizer.TT_EOL:
197                 System.err.println("warning: unexpected EOL token"); break;
198             case StreamTokenizer.TT_NUMBER:
199                 break;
200             case ',':
201                 break out;
202             case StreamTokenizer.TT_WORD:
203                 if (p.sval.endsWith(":")) outString.append(p.sval + " ");
204                 else if (prefixSuffixT.get(p.sval.toLowerCase()) == null) {
205                     if (!lastOnly) {
206                         if (lastInitialHold != null) outString.append(lastInitialHold);
207                         lastInitialHold = p.sval.substring(0,1)+". ";
208                     }
209                     lastNameHold = p.sval;
210                 }
211                 break;
212             default:
213                 break;
214             }
215             }
216             outString.append(lastNameHold);
217         } catch (IOException JavaDoc e) {
218             e.printStackTrace();
219         }
220         return outString.toString();
221     }
222     
223 } // end of class StringLib
224
Popular Tags