Skip to main content
summaryrefslogtreecommitdiffstats
blob: 34cc6bdaa2089f1a01537de012946fc1f916f967 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*******************************************************************************
 * Copyright (c) 2005, 2007 committers of openArchitectureWare and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     committers of openArchitectureWare - initial API and implementation
 *******************************************************************************/
package org.eclipse.internal.xtend.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.NumberFormat;

/**
 * This class is a collection of helper functions for string handling.
 * 
 * @author Arno Haase
 */
public class StringHelper {
	private static final NumberFormat _numFormat = NumberFormat.getNumberInstance();

	/**
	 * formats a number using the default locale settings.
	 */
	public static String prettyPrint(final long num) {
		return _numFormat.format(num);
	}

	/**
	 * formats a number using the default locale settings.
	 */
	public static String prettyPrint(final Number num) {
		return _numFormat.format(num);
	}

	/**
	 * formats a date using the default locale settings.
	 */
	public static String prettyPrint(final Date date) {
		return DateFormat.getDateTimeInstance().format(date);
	}

	/**
	 * returns a new string in which one search string is replaced by another.
	 */
	public static String replace(final String src, final String search, final String replace) {
		if (src == null) {
			return src;
		}
		if ((search == null) || (search.length() == 0)) {
			throw new IllegalArgumentException("Search string must not be empty");
		}

		String result = src;
		int ind = 0;
		while ((ind = result.indexOf(search, ind)) >= 0) {
			result = result.substring(0, ind) + replace + result.substring(ind + search.length());
			ind += replace.length();
		}

		return result;
	}

	/**
	 * replaces special characters that affect formatting with non-formatting character sequences.
	 * <ul>
	 * <li>\ -> \\
	 * <li>&lt;tab&gt; -> \t
	 * <li>&lt;CR&gt; -> \r
	 * <li>&lt;Newline&gt; -> \n
	 * </ul>
	 */
	public static String escape(final String src) {
		String result = replace(src, "\\", "\\\\");
		result = replace(result, "\t", "\\t");
		result = replace(result, "\r", "\\r");
		result = replace(result, "\n", "\\n");
		result = replace(result, "\"", "\\\"");

		return result;
	}

	/**
	 * undoes the operations of <code>escape</code>
	 */
	public static String unescape(final String src) {
		if (src == null) {
			return null;
		}

		final StringBuffer result = new StringBuffer();
		for (int i = 0; i < src.length(); i++) {
			final char curChar = src.charAt(i);

			if (curChar != '\\') {
				result.append(curChar);
				continue;
			}
			// increment i to skip to the character after '\\'
			i++;
			if (i >= src.length()) {
				throw new IllegalArgumentException("String ends with '\\'");
			}

			result.append(unescapeChar(src.charAt(i)));
		}

		return result.toString();
	}

	private static char unescapeChar(final char escapedChar) {
		switch (escapedChar) {
		case '\\':
			return '\\';
		case 'n':
			return '\n';
		case 'r':
			return '\r';
		case 't':
			return '\t';
		case '"':
			return '"';
		}
		throw new IllegalArgumentException("unsupported string format: '\\" + escapedChar + "' is not supported.");
	}

	/**
	 * truncates a string regardless of its length. This method is a workaround for a shortcoming of String.substring (int, int) that is unable to
	 * handle the case where the number of characters would extend beyond the end of the string.
	 */
	public static String truncate(final String str, final int maxLen) {
		if ((str == null) || (str.length() < maxLen)) {
			return str;
		}
		if (maxLen < 0) {
			return "";
		}
		return str.substring(0, maxLen);
	}

	/**
	 * same as String.substring, except that this version handles the case robustly when the index is out of bounds.
	 */
	public static String substring(final String str, final int beginIndex) {
		if (str == null) {
			return null;
		}
		if (beginIndex < 0) {
			return str;
		}
		if (beginIndex >= str.length()) {
			return "";
		}

		return str.substring(beginIndex);
	}

	/**
	 * same as {@link String#substring(int, int)}, except that this version handles the case robustly when one or both of the indexes is out of
	 * bounds.
	 */
	public static String substring(final String str, final int beginIndex, final int endIndex) {
		if (str == null) {
			return null;
		}
		if (beginIndex > endIndex) {
			return "";
		}
		int _beginIndex = beginIndex >= 0 ? beginIndex : 0;
		int _endIndex = endIndex <= str.length() ? endIndex : str.length();

		return str.substring(_beginIndex, _endIndex);
	}

	/**
	 * removes a number of characters from the beginning and the end of a string
	 */
	public static String strip(final String s, final int numStart, final int numEnd) {
		if (s == null) {
			return s;
		}

		return substring(s, numStart, s.length() - numEnd);
	}

	/**
	 * returns the number of occurrences of a character in a string
	 */
	public static int numMatches(final String s, final char ch) {
		if (s == null) {
			return 0;
		}

		int result = 0;
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == ch) {
				result++;
			}
		}

		return result;
	}

	/**
	 * returns the number of occurrences of a substring in a string
	 */
	public static int numMatches(final String s, final String search) {
		if ((s == null) || (search == null) || "".equals(s) || "".equals(search)) {
			return 0;
		}

		int result = 0;
		int curIndex = 0;
		while (true) {
			curIndex = s.indexOf(search, curIndex);
			if (curIndex == -1) {
				break;
			}

			curIndex++;
			result++;
		}
		return result;
	}

	/**
	 * tests if a string starts with any one of a collection of prefixes
	 */
	public static boolean startsWithAny(final String str, final Collection<String> prefixes) {
		if (str == null) {
			return false;
		}

		for (String string : prefixes) {
			if (str.startsWith(string)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * tests if a string starts with any one of a collection of prefixes
	 */
	public static boolean startsWithAny(final String str, final String[] prefixes) {
		if (str == null) {
			return false;
		}

		for (String prefixe : prefixes) {
			if (str.startsWith(prefixe)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * tests if a string ends with any one of a collection of prefixes
	 */
	public static boolean endsWithAny(final String str, final Collection<String> prefixes) {
		if (str == null) {
			return false;
		}

		for (String string : prefixes) {
			if (str.endsWith(string)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * tests if a string ends with any one of a collection of prefixes
	 */
	public static boolean endsWithAny(final String str, final String[] prefixes) {
		if (str == null) {
			return false;
		}

		for (String prefixe : prefixes) {
			if (str.endsWith(prefixe)) {
				return true;
			}
		}
		return false;
	}

	public static String firstUpper(final String str) {
		if (str.length() > 0) {
			return str.substring(0, 1).toUpperCase().concat(str.substring(1));
		}
		return "";
	}

	public static String firstLower(final String str) {
		if (str.length() > 0) {
			return str.substring(0, 1).toLowerCase().concat(str.substring(1));
		}
		return "";
	}

	/**
	 * Splits a string around matches of the given delimiter character.
	 * <p>
	 * This method works similar to {@link String#split(String)} but does not treat the delimiter as a regular expression. This makes it perform
	 * better in most cases where this feature is not necessary. Furthermore this implies that trailing empty segments will not be part of the result.
	 * <p>
	 * Copied from org.eclipse.xtext.util.Strings
	 * 
	 * @param value
	 *            the string to split
	 * @param delimiter
	 *            the delimiting String (e.g. '.' or ':' or '::')
	 * 
	 * @return the list of strings computed by splitting the string around matches of the given delimiter without trailing empty segments. Never
	 *         <code>null</code> and the list does not contain any <code>null</code> values.
	 * 
	 * @throws NullPointerException
	 *             If the {@code value} is {@code null}
	 * @see String#split(String)
	 * @since 1.4
	 */
	public static List<String> split(final String value, final String delimiter) {
		List<String> result = new ArrayList<String>();
		int lastIndex = 0;
		int index = value.indexOf(delimiter, lastIndex);
		int pendingEmptyStrings = 0;
		while (index != -1) {
			String addMe = value.substring(lastIndex, index);
			if (addMe.length() == 0) {
				pendingEmptyStrings++;
			} else {
				while (pendingEmptyStrings > 0) {
					result.add("");
					pendingEmptyStrings--;
				}
				result.add(addMe);
			}
			lastIndex = index + delimiter.length();
			index = value.indexOf(delimiter, lastIndex);
		}
		if (lastIndex != value.length()) {
			while (pendingEmptyStrings > 0) {
				result.add("");
				pendingEmptyStrings--;
			}
			result.add(value.substring(lastIndex));
		}
		return result;
	}

}

Back to the top