1 61 62 63 package org.jaxen.function; 64 65 import java.util.List ; 66 67 import org.jaxen.Context; 68 import org.jaxen.Function; 69 import org.jaxen.FunctionCallException; 70 import org.jaxen.Navigator; 71 72 89 public class StringLengthFunction implements Function 90 { 91 92 93 96 public StringLengthFunction() {} 97 98 99 113 public Object call(Context context, 114 List args) throws FunctionCallException 115 { 116 if (args.size() == 0) 117 { 118 return evaluate( context.getNodeSet(), 119 context.getNavigator() ); 120 } 121 else if (args.size() == 1) 122 { 123 return evaluate( args.get(0), 124 context.getNavigator() ); 125 } 126 127 throw new FunctionCallException( "string-length() requires one argument." ); 128 } 129 130 143 public static Double evaluate(Object obj, Navigator nav) throws FunctionCallException 144 { 145 146 String str = StringFunction.evaluate( obj, nav ); 148 char[] data = str.toCharArray(); 150 int length = 0; 151 for (int i = 0; i < data.length; i++) { 152 char c = data[i]; 153 length++; 154 if (c >= 0xD800) { 157 try { 158 char low = data[i+1]; 159 if (low < 0xDC00 || low > 0xDFFF) { 160 throw new FunctionCallException("Bad surrogate pair in string " + str); 161 } 162 i++; } 164 catch (ArrayIndexOutOfBoundsException ex) { 165 throw new FunctionCallException("Bad surrogate pair in string " + str); 166 } 167 } 168 } 169 return new Double (length); 170 } 171 172 } 173 | Popular Tags |