KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > util > StringUtil


1 /*
2  * Copyright (C) The Apache Software Foundation. All rights reserved.
3  *
4  * This software is published under the terms of the Apache Software License
5  * version 1.1, a copy of which has been included with this distribution in
6  * the LICENSE.txt file.
7  */

8 package org.apache.avalon.excalibur.util;
9
10 import java.util.ArrayList JavaDoc;
11 import java.util.StringTokenizer JavaDoc;
12
13 /**
14  * A set of utility operations that work on or create strings.
15  *
16  * @author <a HREF="mailto:peter@apache.org">Peter Donald</a>
17  * @version CVS $Revision: 1.12 $ $Date: 2001/12/31 21:36:50 $
18  */

19 public final class StringUtil
20 {
21     /**
22      * the line separator for this OS
23      */

24     public final static String JavaDoc LINE_SEPARATOR = System.getProperty( "line.separator" );
25
26     private final static String JavaDoc SPACE_16 = " ";
27     private final static String JavaDoc SPACE_8 = " ";
28     private final static String JavaDoc SPACE_4 = " ";
29     private final static String JavaDoc SPACE_2 = " ";
30     private final static String JavaDoc SPACE_1 = " ";
31
32     ///Private Constructor to block instantiation
33
private StringUtil()
34     {
35     }
36
37     /**
38      * Convenience utility to concatenate three strings together.
39      */

40     public final static String JavaDoc concat( final String JavaDoc first,
41                                        final String JavaDoc second,
42                                        final String JavaDoc third )
43     {
44         return new StringBuffer JavaDoc(first).append(second).append(third).toString();
45     }
46
47     /**
48      * Convenience utility to concatenate an array of strings together.
49      */

50     public final static String JavaDoc concat( final String JavaDoc[] list )
51     {
52         final StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
53
54         for (int i = 0; i < list.length; i++)
55         {
56             buffer.append(list[i]);
57         }
58
59         return buffer.toString();
60     }
61
62     /**
63      * Replace substrings of one string with another string and return altered string.
64      *
65      * @param original input string
66      * @param oldString the substring section to replace
67      * @param newString the new substring replacing old substring section
68      * @return converted string
69      */

70     public final static String JavaDoc replaceSubString( final String JavaDoc original,
71                                                  final String JavaDoc oldString,
72                                                  final String JavaDoc newString )
73     {
74         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
75
76         int end = original.indexOf( oldString );
77         int start = 0;
78         final int stringSize = oldString.length();
79
80         while( end != -1 )
81         {
82             sb.append( original.substring( start, end ) );
83             sb.append( newString );
84             start = end + stringSize;
85             end = original.indexOf( oldString, start );
86         }
87
88         end = original.length();
89         sb.append( original.substring( start, end ) );
90
91         return sb.toString();
92     }
93
94     /**
95      * Display bytes in hex format.
96      * <p>The display puts hex display on left and then writes out
97      * textual representation on right. The text replaces any
98      * non-printing character with a '.'</p>
99      *
100      * <p>Note that this code was based on work done by Barry Peterson
101      * on the Q2Java project</p>
102      *
103      * @param data the bytes to display
104      * @param length the number of bytes to display per line
105      * @return The display string
106      */

107     public final static String JavaDoc hexDisplay( final byte[] data, final int length )
108     {
109         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
110
111         for( int i = 0; i < length; i += 16 )
112         {
113             //int lineEnd = Math.min( i+16, fArrayLength );
114
int lineSize = Math.min( 16, length - i );
115             final int lineEnd = lineSize + i;
116
117             for( int j = i; j < lineEnd; j++)
118             {
119                 final int value = data[ j ] & 0xFF;
120
121                 if( value < 16 ) sb.append( '0' );
122                 sb.append( Integer.toHexString( value ) );
123                 sb.append( ' ' );
124             }
125
126             int padcount = 16 - lineSize;
127             while( padcount > 0 )
128             {
129                 padcount--;
130                 sb.append( " " );
131             }
132
133             sb.append( " " );
134
135             for( int j = i; j < lineEnd; j++ )
136             {
137                 final int value = data[ j ] & 0xFF;
138
139                 //Shouldn't 255 be lower????????
140
if( (value < 32) || (value > 255) ) sb.append( '.' );
141                 else sb.append( (char)value );
142             }
143
144             sb.append( '\n' );
145         }
146
147         return sb.toString();
148     }
149
150     /**
151      * Truncate a string to maximum length;
152      *
153      * @param string the string
154      * @param length the length
155      * @return a truncated string or original string if it is short enough
156      */

157     public final static String JavaDoc truncate( final String JavaDoc string, final int length )
158     {
159         if( length >= string.length() ) return string;
160         else return string.substring( 0, length );
161     }
162
163     /**
164      * Truncate a string in a nice manner.
165      * The method will attempt to truncate the string
166      * on whitespace and append "..." to the end.
167      *
168      * @author <a HREF="mailto:nate@protomatter.com">Nate Sammons</a>
169      */

170     public final static String JavaDoc truncateNicely( final String JavaDoc string, final int length )
171     {
172         if( length >= string.length() ) return string;
173         else if( 3 >= length )
174         {
175             final StringBuffer JavaDoc sb = new StringBuffer JavaDoc( length );
176             for( int i = 0; i < length; i++ ) sb.append( '.' );
177             return sb.toString();
178         }
179
180         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc( length );
181         getIndexOfBreak( sb, string, 0, length - 3, true );
182         sb.append( "..." );
183
184         return sb.toString();
185     }
186
187     /**
188      * Wordwrap string to specified column.
189      * if force is true then words that exceed column length will be
190      * cut otherwise each word will exist on a line by itself.
191      *
192      * @param string string to word-wrap
193      * @param column the column at which to wrap
194      * @param force true if string should be force split at column
195      * @return The word-wrapped string
196      */

197     public final static String JavaDoc wordWrap( final String JavaDoc string, final int column, final boolean force )
198     {
199         final int length = string.length();
200         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
201
202         int start = 0;
203         int end = getIndexOfBreak( sb, string, start, column, force );
204
205         while( length != end )
206         {
207             //TODO: Make this EOL parameterizable
208
sb.append( "\n" );
209
210             start = end;
211
212             end = getIndexOfBreak( sb, string, start, column, force );
213         }
214
215         return sb.toString();
216     }
217
218     /**
219      * Splits the string on every token into an array of strings.
220      *
221      * @param string the string
222      * @param onToken the token
223      * @return the resultant array
224      */

225     public final static String JavaDoc[] split( final String JavaDoc string, final String JavaDoc onToken )
226     {
227         final StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc( string, onToken );
228         final String JavaDoc[] result = new String JavaDoc[ tokenizer.countTokens() ];
229
230         for( int i = 0; i < result.length; i++ )
231         {
232             result[ i ] = tokenizer.nextToken();
233         }
234
235         return result;
236     }
237
238     /**
239      * Joins the string array using specified separator.
240      *
241      * @param strings the array of strings to join
242      * @param separator the separator to use when joining
243      * @return the joined string
244      */

245     public final static String JavaDoc join( final String JavaDoc[] strings, final String JavaDoc separator )
246     {
247         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
248         for( int i = 0; i < strings.length; i++ )
249         {
250             sb.append( strings[ i ] );
251             sb.append( separator );
252         }
253
254         return sb.toString();
255     }
256
257     /**
258      * Utility to format a string given a set of constraints.
259      * TODO: Think of a better name than format!!!! ;)
260      *
261      * @param minSize the minimum size of output (0 to ignore)
262      * @param maxSize the maximum size of output (0 to ignore)
263      * @param rightJustify true if the string is to be right justified in it's box.
264      * @param string the input string
265      */

266     public final static String JavaDoc format( final int minSize,
267                                        final int maxSize,
268                                        final boolean rightJustify,
269                                        final String JavaDoc string )
270     {
271         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc( maxSize );
272         format( sb, minSize, maxSize, rightJustify, string );
273         return sb.toString();
274     }
275
276     /**
277      * Utility to format a string given a set of constraints.
278      * TODO: Think of a better name than format!!!! ;)
279      * Note this was thieved from the logkit project.
280      *
281      * @param sb the StringBuffer
282      * @param minSize the minimum size of output (0 to ignore)
283      * @param maxSize the maximum size of output (0 to ignore)
284      * @param rightJustify true if the string is to be right justified in it's box.
285      * @param string the input string
286      */

287     public final static void format( final StringBuffer JavaDoc sb,
288                                      final int minSize,
289                                      final int maxSize,
290                                      final boolean rightJustify,
291                                      final String JavaDoc string )
292     {
293         final int size = string.length();
294
295         if( size < minSize )
296         {
297             //assert( minSize > 0 );
298
if( rightJustify )
299             {
300                 appendWhiteSpace( sb, minSize - size );
301                 sb.append( string );
302             }
303             else
304             {
305                 sb.append( string );
306                 appendWhiteSpace( sb, minSize - size );
307             }
308         }
309         else if( maxSize > 0 && maxSize < size )
310         {
311             if( rightJustify )
312             {
313                 sb.append( string.substring( size - maxSize ) );
314             }
315             else
316             {
317                 sb.append( string.substring( 0, maxSize ) );
318             }
319         }
320         else
321         {
322             sb.append( string );
323         }
324     }
325
326     /**
327      * Append a certain number of whitespace characters to a StringBuffer.
328      *
329      * @param sb the StringBuffer
330      * @param length the number of spaces to append
331      */

332     public final static void appendWhiteSpace( final StringBuffer JavaDoc sb, int length )
333     {
334         while( length >= 16 )
335         {
336             sb.append( SPACE_16 );
337             length -= 16;
338         }
339
340         if( length >= 8 )
341         {
342             sb.append( SPACE_8 );
343             length -= 8;
344         }
345
346         if( length >= 4 )
347         {
348             sb.append( SPACE_4 );
349             length -= 4;
350         }
351
352         if( length >= 2 )
353         {
354             sb.append( SPACE_2 );
355             length -= 2;
356         }
357
358         if( length >= 1 )
359         {
360             sb.append( SPACE_1 );
361             length -= 1;
362         }
363     }
364
365     /**
366      * Get index of good place to break line.
367      * The index is the last whitespace character.
368      *
369      * @param string the input string
370      * @param start the start index of line
371      * @param maxCount the max size of the line
372      * @return the index to break line
373      */

374     private final static int getIndexOfBreak( final StringBuffer JavaDoc sb,
375                                               final String JavaDoc string,
376                                               final int start,
377                                               final int maxCount,
378                                               final boolean forceBreak )
379     {
380
381         final int end = string.length() - start;
382         int max = Math.min( maxCount, end );
383
384         int base = 0;
385         for( int i = 0; i < max; i++ )
386         {
387             final int index = start + i;
388             final char ch = string.charAt( index );
389             if( !Character.isWhitespace( ch ) ) break;
390
391             base = i + 1;
392         }
393
394         max += base;
395
396         int breakIndex = -1;
397         for( int i = base; i < max; i++ )
398         {
399             final int index = start + i;
400             final char ch = string.charAt( index );
401
402             if( Character.isWhitespace( ch ) ) breakIndex = index;
403         }
404
405         if( -1 != breakIndex )
406         {
407             final String JavaDoc part = string.substring( start + base, breakIndex );
408             sb.append( part );
409             return breakIndex + 1;
410         }
411         else
412         {
413             if( forceBreak )
414             {
415                 final String JavaDoc part = string.substring( start + base, start + max );
416                 sb.append( part );
417
418                 return start + max;
419             }
420             else
421             {
422                 return getIndexOfBreak( sb, string, start, Integer.MAX_VALUE, true );
423             }
424         }
425     }
426 }
427
Popular Tags