Skip to main content
summaryrefslogtreecommitdiffstats
blob: 1fc32276ea72b2b2eb2839c0eedeff151b89c8e0 (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
/*******************************************************************************
 * 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.text.DateFormat;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

/**
 * 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(long num) {
		return _numFormat.format(num);
	}

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

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

	/**
	 * returns a new string in which one search string is replaced by another.
	 */
	public static String replace(String src, String search, 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(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(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(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(String str, 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(String str, int beginIndex) {
		if (str == null)
			return null;
		if (beginIndex < 0)
			return str;
		if (beginIndex >= str.length())
			return "";

		return str.substring(beginIndex);
	}

	/**
	 * same as String.substring, except that this version handles the case
	 * robustly when one or both of the indexes is out of bounds.
	 */
	public static String substring(String str, int beginIndex, int endIndex) {
		if (str == null)
			return null;
		if (beginIndex > endIndex)
			return "";
		if (beginIndex < 0)
			beginIndex = 0;
		if (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(String s, int numStart, 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(String s, 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(String s, 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(String str, Collection<String> prefixes) {
		if (str == null)
			return false;

		for (Iterator<String> iter = prefixes.iterator(); iter.hasNext();) {
			if (str.startsWith(iter.next()))
				return true;
		}
		return false;
	}

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

		for (int i = 0; i < prefixes.length; i++) {
			if (str.startsWith(prefixes[i]))
				return true;
		}
		return false;
	}

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

		for (Iterator<String> iter = prefixes.iterator(); iter.hasNext();) {
			if (str.endsWith(iter.next()))
				return true;
		}
		return false;
	}

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

		for (int i = 0; i < prefixes.length; i++) {
			if (str.endsWith(prefixes[i]))
				return true;
		}
		return false;
	}

	public static String firstUpper(String str) {
		return str.substring(0, 1).toUpperCase().concat(str.substring(1));
	}

	public static String firstLower(String str) {
		return str.substring(0, 1).toLowerCase().concat(str.substring(1));
	}
}

Back to the top