1 package com.protomatter.util; 2 3 52 53 import java.util.*; 54 55 58 public class StringUtil 59 { 60 63 private StringUtil() 64 { 65 super(); 66 } 67 68 72 public static void pad(StringBuffer b, String s, int n) 73 { 74 int l = s.length(); 75 if (l == n) 76 { 77 b.append(s); 78 return; 79 } 80 else if (l > n) 81 { 82 b.append(s.substring(0, n)); 83 return; 84 } 85 else 86 { 87 b.append(s.substring(0, l)); 88 while (l++<n) 89 b.append(' '); 90 return; 91 } 92 } 93 94 98 public static String pad(String s, int n) 99 { 100 int l = s.length(); 101 if (l == n) 102 return s; 103 else if (l > n) 104 return s.substring(0, n); 105 else 106 { 107 char[] carr = new char[n]; 108 s.getChars(0, l, carr, 0); 109 while (l<n) 110 carr[l++] = ' '; 111 return new String (carr); 112 } 113 } 114 115 120 public static String truncate(String s, int n) 121 { 122 if (s.length() <= n) 123 return s; 124 else 125 return s.substring(0, n); 126 } 127 128 133 public static String truncateNicely(String s, int n) 134 { 135 if (n <= 3) 136 { 137 StringBuffer b = new StringBuffer (n); 138 for (int i=0; i<n; i++) 139 b.append("."); 140 return b.toString(); 141 } 142 int sublen = n-3; 143 StringBuffer clippedtext = new StringBuffer (); 144 StringTokenizer st = new StringTokenizer(s); 145 while (st.hasMoreTokens()) 146 { 147 String word = st.nextToken(); 148 int cliplen = clippedtext.length(); 149 if(word.length() + cliplen + 1 <= sublen) 150 { 151 if (cliplen == 0) 152 { 153 clippedtext.append(word); 154 } 155 else 156 { 157 clippedtext.append(" "); 158 clippedtext.append(word); 159 } 160 } 161 else 162 { 163 if(clippedtext.length() == 0) 164 clippedtext.append(s.substring(0,sublen)); 165 clippedtext.append("..."); 166 break; 167 } 168 } 169 return clippedtext.toString(); 170 } 171 172 public static String replace(String inputString, String token, String replacement) 173 { 174 int index = 0; 175 int replacementLength = replacement.length(); 176 int tokenLength = token.length(); 177 String input = inputString; 178 while (true) 179 { 180 index = input.indexOf(token, index); 181 if (index == -1) 182 { 183 return input; 184 } 185 StringBuffer buf = new StringBuffer (input.length() + replacementLength); 186 buf.append(input.substring(0, index)); 187 buf.append(replacement); 188 buf.append(input.substring(index + tokenLength)); 189 input = buf.toString(); 190 } 191 } 192 } 193 | Popular Tags |