01: package com.jat.util;
02:
03: /**
04: * <p>Title: JAT</p>
05: * <p>Description: </p>
06: * <p>Copyright: Copyright (c) 2004 -2005 Stefano Fratini (stefano.fratini@gmail.com)</p>
07: * <p>Distributed under the terms of the GNU Lesser General Public License, v2.1 or later</p>
08: * @author stf
09: * @version 1.1
10: */
11:
12: public class StringUtil {
13:
14: public static String replace(String str, String pattern1,
15: String pattern2) {
16: String ret = null;
17: int index = str.indexOf(pattern1);
18: if (index > -1) {
19: ret = str.substring(0, index);
20: ret += pattern2;
21: ret += str.substring(index + pattern1.length());
22: }
23: return ret;
24: }
25:
26: public static String replaceAll(String str, String pattern1,
27: String pattern2) {
28: String ret = new String(str);
29: while (ret.indexOf(pattern1) > -1)
30: ret = replace(ret, pattern1, pattern2);
31: return ret;
32: }
33:
34: public static String replace(String str, String pattern1,
35: String pattern2, int index) throws Exception {
36: int i = 0;
37: String mainStr = new String(str);
38: int pos = 0;
39: do {
40: pos = mainStr.indexOf(pattern1);
41: mainStr = mainStr.substring(pos + pattern1.length());
42: i++;
43: } while (pos > -1 && i < index);
44: if (index != i || pos < 0)
45: throw new Exception("No such " + index + "th pattern '"
46: + pattern1 + "' in '" + str + "'");
47: int firstPartIndex = str.indexOf(mainStr);
48: if (firstPartIndex < 1)
49: firstPartIndex = str.length();
50: String firstPart = str.substring(0, firstPartIndex
51: - pattern1.length());
52: String secondPart = pattern2 + mainStr;
53: return firstPart + secondPart;
54: }
55:
56: public static boolean less(String s1, String s2) {
57: int size = s1.length() < s2.length() ? s1.length() : s2
58: .length();
59: if (size == 0)
60: return s1.length() == 0;
61: try {
62: if (Character.isDigit(s1.charAt(0))
63: && Character.isDigit(s2.charAt(0))) {
64: long n1 = getInitialLong(s1);
65: long n2 = getInitialLong(s2);
66: if (n1 == n2)
67: return less(getNextSubstring(s1, n1),
68: getNextSubstring(s2, n2));
69: return n1 < n2;
70: }
71: } catch (Exception ignored) {
72: }
73: if (s1.charAt(0) == s2.charAt(0) && s1.length() > 1
74: && s2.length() > 1)
75: return less(s1.substring(1), s2.substring(1));
76: else if (s1.charAt(0) < s2.charAt(0))
77: return true;
78: else if (s1.charAt(0) > s2.charAt(0))
79: return false;
80: else
81: return s1.length() < s2.length();
82: }
83:
84: static long getInitialLong(String str) throws Exception {
85: int i = 0;
86: String ret = "";
87: while (i < str.length() && Character.isDigit(str.charAt(i))) {
88: ret += str.charAt(i);
89: i++;
90: }
91: return Long.parseLong(ret);
92: }
93:
94: private static String getNextSubstring(String str, long num) {
95: String s = "" + num;
96: return str.substring(s.length());
97: }
98: }
|