KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > uka > ipd > coverage > utils > StringFormatter


1 /*
2  * Created on Aug 14, 2004
3  * @author Matthias Kempka
4  */

5 package de.uka.ipd.coverage.utils;
6
7 import java.util.StringTokenizer JavaDoc;
8
9 /**
10  * @author Matthias Kempka
11  *
12  */

13 public class StringFormatter {
14     
15     /**
16      * replaces all occurrences of "{i}" in toFormat with substituters[i] with
17      * i starting from 0 up to substituters.length-1.
18      * Expressions of "{i:j}" are replaced with substituters[i] and filled up
19      * with whitespaces such that j spaces are used.
20      * replaces "\\{" with "{".
21      * @param toFormat
22      * @param substituters
23      */

24     public static String JavaDoc format(String JavaDoc toFormat, Object JavaDoc[] substituters) {
25         int currentMatch = 0;
26         int currentMatchEnd = 0;
27         while ((currentMatch = toFormat.indexOf("{", currentMatch)) != -1) { //$NON-NLS-1$
28
if (currentMatch > 0 && toFormat.charAt(currentMatch - 1) == '\\') {
29                 continue;
30             }
31             currentMatchEnd = toFormat.indexOf("}", currentMatch); //$NON-NLS-1$
32
if (currentMatchEnd == -1) {
33                 throw new IllegalArgumentException JavaDoc("\'{\' given without \'}\'"); //$NON-NLS-1$
34
}
35             String JavaDoc formatAssignment = toFormat.substring(
36                     currentMatch + 1, currentMatchEnd);
37             String JavaDoc replacement = generateReplacement(substituters, formatAssignment);
38             String JavaDoc newEnd = replacement.concat(toFormat.substring(
39                     currentMatchEnd + 1, toFormat.length()));
40             toFormat = toFormat.substring(0, currentMatch).concat(newEnd);
41             currentMatch = currentMatch + replacement.length();
42         }
43         toFormat = toFormat.replaceAll("\\{", "{"); //$NON-NLS-1$ //$NON-NLS-2$
44
toFormat = toFormat.replaceAll("\\}", "}"); //$NON-NLS-1$ //$NON-NLS-2$
45
return toFormat;
46     }
47     
48     /**
49      * @param substituters
50      * @param formatAssignment
51      */

52     private static String JavaDoc generateReplacement(Object JavaDoc[] substituters, String JavaDoc formatAssignment) {
53         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(
54                 formatAssignment, ":"); //$NON-NLS-1$
55
int substPos = Integer.parseInt(tokenizer.nextToken());
56         String JavaDoc replacement = substituters[substPos].toString();
57         int length = replacement.length();
58         if (tokenizer.hasMoreTokens()) {
59             length = Integer.parseInt(tokenizer.nextToken());
60         }
61         while (length > substituters[substPos].toString().length()) {
62             replacement = replacement + " "; //$NON-NLS-1$
63
length--;
64         }
65         return replacement;
66     }
67
68 }
69
Popular Tags