Rewrite inefficient string functions
[cql-java-moved-to-github.git] / src / main / java / org / z3950 / zing / cql / Utils.java
index 6777e46..9224d36 100644 (file)
@@ -22,30 +22,25 @@ class Utils {
     // s/&/&/g;
     // s/</&lt;/g;
     // s/>/&gt;/g;
-    // This is hideously inefficient, but I just don't see a better
-    // way using the standard JAVA library.
-    //
     static String xq(String str) {
-       str = replaceString(str, "&", "&amp;");
-       str = replaceString(str, "<", "&lt;");
-       str = replaceString(str, ">", "&gt;");
-       return str;
-    }
-
-    // I can't _believe_ I have to write this by hand in 2002 ...
-    static String replaceString(String str, String from, String to) {
-       StringBuffer sb = new StringBuffer();
-       int ix;                 // index of next `from'
-       int offset = 0;         // index of previous `from' + length(from)
-
-       while ((ix = str.indexOf(from, offset)) != -1) {
-           sb.append(str.substring(offset, ix));
-           sb.append(to);
-           offset = ix + from.length();
-       }
-
-       // End of string: append last bit and we're done
-       sb.append(str.substring(offset));
+        StringBuilder sb = new StringBuilder();
+        for(int i = 0; i<str.length(); i++) {
+            char c = str.charAt(i);
+            switch (c) {
+                case '<':
+                    sb.append("&lt;");
+                    break;
+                case '>':
+                    sb.append("&gt;");
+                    break;
+                case '&':
+                    sb.append("&amp;");
+                    break;
+                default:
+                    sb.append(c);
+            }
+        }
        return sb.toString();
     }
+
 }