1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package net.sf.morph.util;
16
17 import java.lang.reflect.Array;
18 import java.util.Collection;
19 import java.util.Iterator;
20 import java.util.List;
21
22 import net.sf.morph.Morph;
23
24 /**
25 * @author Matt Sgarlata
26 * @since Mar 11, 2005
27 */
28 public class StringUtils {
29
30
31
32 public static int numOccurrences(String toSearch, String searchFor) {
33 if (toSearch == null && searchFor == null) {
34 return 0;
35 }
36 if (searchFor == null || searchFor.length() == 0) {
37 return 0;
38 }
39 int matchingIndex = 0;
40 int numOccurrences = 0;
41 for (int i=0; i<toSearch.length(); i++) {
42 if (toSearch.charAt(i) == searchFor.charAt(matchingIndex)) {
43 if (matchingIndex == searchFor.length() -1) {
44 matchingIndex = 0;
45 numOccurrences++;
46 }
47 else {
48 matchingIndex++;
49 }
50 }
51 }
52 return numOccurrences;
53 }
54
55 public static String repeat(String str, int repititions) {
56 int size = repititions * (str == null ? 0 : str.length());
57 StringBuffer buffer = new StringBuffer(size);
58 for (int i=0; i<repititions; i++) {
59 buffer.append(str);
60 }
61 return buffer.toString();
62 }
63
64 public static String englishJoin(Object values) {
65 if (values == null) {
66 return null;
67 }
68 StringBuffer buffer = new StringBuffer();
69 int length = Array.getLength(values);
70 for (int i = 0; i < length; i++) {
71 buffer.append(Array.get(values, i));
72 if (i < length - 2) {
73 buffer.append(", ");
74 }
75 if (i == length - 2) {
76 buffer.append(" and ");
77 }
78 }
79 return buffer.toString();
80 }
81
82 public static String englishJoin(Collection values) {
83 return englishJoin(values.toArray(new Object[values.size()]));
84 }
85
86 public static String removeWhitespace(String expression) {
87 if (expression == null) {
88 return null;
89 }
90
91
92
93 for (int i=0; i<expression.length(); i++) {
94 if (Character.isWhitespace(expression.charAt(i))) {
95 return constructStringWithoutWhitespace(expression);
96 }
97 }
98
99 return expression;
100 }
101
102 private static String constructStringWithoutWhitespace(String expression) {
103 StringBuffer buffer = new StringBuffer(expression.length());
104 for (int i=0; i<expression.length(); i++) {
105 if (!Character.isWhitespace(expression.charAt(i))) {
106 buffer.append(expression.charAt(i));
107 }
108 }
109 return buffer.toString();
110 }
111
112 public static String join(Object object, String separator) {
113 if (object == null) {
114 return null;
115 }
116
117
118 StringBuffer idBuff = new StringBuffer();
119 boolean firstIteration = true;
120 Collection collection = (Collection) Morph.convert(List.class, object);
121 for (Iterator iter = collection.iterator(); iter.hasNext();) {
122 if (firstIteration) {
123 firstIteration = false;
124 }
125 else {
126 idBuff.append(separator);
127 }
128 idBuff.append(iter.next());
129 }
130 return idBuff.toString();
131 }
132
133 public static String join(Object object) {
134 return join(object, ", ");
135 }
136
137 }