1 5 package de.uka.ipd.coverage.utils; 6 7 import java.util.StringTokenizer ; 8 9 13 public class StringFormatter { 14 15 24 public static String format(String toFormat, Object [] substituters) { 25 int currentMatch = 0; 26 int currentMatchEnd = 0; 27 while ((currentMatch = toFormat.indexOf("{", currentMatch)) != -1) { if (currentMatch > 0 && toFormat.charAt(currentMatch - 1) == '\\') { 29 continue; 30 } 31 currentMatchEnd = toFormat.indexOf("}", currentMatch); if (currentMatchEnd == -1) { 33 throw new IllegalArgumentException ("\'{\' given without \'}\'"); } 35 String formatAssignment = toFormat.substring( 36 currentMatch + 1, currentMatchEnd); 37 String replacement = generateReplacement(substituters, formatAssignment); 38 String 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("\\{", "{"); toFormat = toFormat.replaceAll("\\}", "}"); return toFormat; 46 } 47 48 52 private static String generateReplacement(Object [] substituters, String formatAssignment) { 53 StringTokenizer tokenizer = new StringTokenizer ( 54 formatAssignment, ":"); int substPos = Integer.parseInt(tokenizer.nextToken()); 56 String 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 + " "; length--; 64 } 65 return replacement; 66 } 67 68 } 69 | Popular Tags |