1 60 package org.jaxen.function; 61 62 import java.util.List ; 63 64 import org.jaxen.Context; 65 import org.jaxen.Function; 66 import org.jaxen.FunctionCallException; 67 import org.jaxen.Navigator; 68 157 public class SubstringFunction implements Function 158 { 159 160 163 public SubstringFunction() {} 164 165 166 178 public Object call(Context context, 179 List args) throws FunctionCallException 180 { 181 final int argc = args.size(); 182 if (argc < 2 || argc > 3){ 183 throw new FunctionCallException( "substring() requires two or three arguments." ); 184 } 185 186 final Navigator nav = context.getNavigator(); 187 188 final String str = StringFunction.evaluate(args.get(0), nav ); 189 if (str == null) { 191 return ""; 192 } 193 194 final int stringLength = (StringLengthFunction.evaluate(args.get(0), nav )).intValue(); 195 196 if (stringLength == 0) { 197 return ""; 198 } 199 200 Double d1 = NumberFunction.evaluate(args.get(1), nav); 201 202 if (d1.isNaN()){ 203 return ""; 204 } 205 int start = RoundFunction.evaluate(d1, nav).intValue() - 1; 207 208 int substringLength = stringLength; 209 if (argc == 3){ 210 Double d2 = NumberFunction.evaluate(args.get(2), nav); 211 212 if (!d2.isNaN()){ 213 substringLength = RoundFunction.evaluate(d2, nav ).intValue(); 214 } 215 else { 216 substringLength = 0; 217 } 218 } 219 220 if (substringLength < 0) return ""; 221 222 int end = start + substringLength; 223 if (argc == 2) end = stringLength; 224 225 if ( start < 0){ 227 start = 0; 228 } 229 else if (start > stringLength){ 230 return ""; 231 } 232 233 if (end > stringLength){ 234 end = stringLength; 235 } 236 else if (end < start) return ""; 237 238 if (stringLength == str.length()) { 239 return str.substring(start, end); 241 } 242 else { 243 return unicodeSubstring(str, start, end); 244 } 245 246 } 247 248 private static String unicodeSubstring(String s, int start, int end) { 249 250 StringBuffer result = new StringBuffer (s.length()); 251 for (int jChar = 0, uChar=0; uChar < end; jChar++, uChar++) { 252 char c = s.charAt(jChar); 253 if (uChar >= start) result.append(c); 254 if (c >= 0xD800) { jChar++; 258 if (uChar >= start) result.append(s.charAt(jChar)); 259 } 260 } 261 return result.toString(); 262 } 263 } 264
| Popular Tags
|