01: /*
02: * Copyright 2003 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package velosurf.util;
18:
19: /** this class gathers static utility methods for strings
20: *
21: * @author <a href=mailto:claude.brisson@gmail.com>Claude Brisson</a>
22: */
23: public class Strings {
24: /** replace a string by another inside a target string.
25: *
26: * @param target target string
27: * @param oldPattern old pattern
28: * @param newPattern new pattern
29: * @return result
30: */
31: public static String replace(String target, String oldPattern,
32: String newPattern) {
33: if (target == null)
34: return null;
35:
36: if (oldPattern == null || oldPattern.length() == 0
37: || newPattern == null)
38: return target;
39:
40: StringBuffer buff = new StringBuffer();
41: int previous = 0, offset = 0, length = oldPattern.length();
42:
43: while ((offset = target.indexOf(oldPattern, previous)) != -1) {
44: buff.append(target.substring(previous, offset));
45: buff.append(newPattern);
46: previous = offset + length;
47: }
48: buff.append(target.substring(previous));
49:
50: return buff.toString();
51:
52: }
53:
54: /** characters to trim.
55: */
56: private static String trimmed = " \t\r\n";
57:
58: /** trim spaces and EOL characters.
59: *
60: * @param target target string
61: * @return the trimmed string
62: */
63: public static String trimSpacesAndEOL(String target) {
64: if (target == null || target.length() == 0)
65: return target;
66:
67: char c;
68: int i = 0;
69: do {
70: c = target.charAt(i++);
71: } while (trimmed.indexOf(c) != -1 && i < target.length());
72:
73: int j = target.length();
74: if (j > i) {
75: do {
76: c = target.charAt(--j);
77: } while (trimmed.indexOf(c) != -1 && j < target.length());
78: } else
79: j--;
80: return target.substring(i - 1, j + 1);
81: }
82: }
|