-
Notifications
You must be signed in to change notification settings - Fork 3
/
Strings.java
499 lines (470 loc) · 10.9 KB
/
Strings.java
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/*
* Copyright (c) Clarisma / GeoDesk contributors
*
* This source code is licensed under the Apache 2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.clarisma.common.text;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.text.Normalizer;
import java.util.StringJoiner;
import java.util.function.Function;
public class Strings
{
/**
* Checks if a character needs to be escaped, and if so,
* returns its corresponding escape character. When escaping
* entire strings, escape characters need to be preceded
* by a backslash.
*
* @param ch the character to check
* @return its corresponding escape character, or
* `Character.MAX_VALUE` if this character
* does not require escaping
*/
public static char escape(char ch)
{
if(ch < 32)
{
switch(ch)
{
case '\b': return 'b';
case '\n': return 'n';
case '\t': return 't';
case '\f': return 'f';
case '\r': return 'r';
case '\0': return '0';
}
return Character.MAX_VALUE; // TODO: check
}
switch(ch)
{
case '\'':
case '\"':
case '\\':
return ch;
}
return Character.MAX_VALUE;
}
/**
* Turns an escape character into its true character.
*
* @param ch the escape character
* @return the actual character, or `Character.MAX_VALUE`
* if `ch` does not represent a valid escape
* character.
*/
public static char unescape(char ch)
{
switch(ch)
{
case 'b': return '\b';
case 'n': return '\n';
case 't': return '\t';
case 'f': return '\f';
case 'r': return '\r';
case '\'': return '\'';
case '\"': return '\"';
case '\\': return '\\';
case '0': return '\0';
}
return Character.MAX_VALUE;
}
public static String escape (String s)
{
StringBuilder buf = new StringBuilder ();
for (int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
char chEscaped = escape(ch);
if(chEscaped != Character.MAX_VALUE)
{
buf.append('\\');
buf.append(chEscaped);
}
else
{
buf.append (ch);
}
}
return buf.toString ();
}
// This method is much slower than building a new String via StringBuffer
/*
public static void printEscaped (PrintStream out, String s)
{
for (int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
char chEscaped = escape(ch);
if(chEscaped != Character.MAX_VALUE)
{
out.append('\\');
out.append(chEscaped);
}
else
{
out.append (ch);
}
}
}
*/
public static String unescape (String s, boolean trimQuotes)
{
StringBuilder buf = new StringBuilder ();
int len = s.length() - (trimQuotes ? 1 : 0);
int i = trimQuotes ? 1 : 0;
for (; i<len; i++)
{
char ch = s.charAt(i);
if (ch=='\\')
{
i++;
if(i >= len) break;
buf.append(unescape(s.charAt(i)));
}
else
{
buf.append(ch);
}
}
return buf.toString();
}
/**
* Checks if a string represents a valid number, and if so,
* whether it is integral or floating-point.
*
* @param s the string to check
* @return `Double.class` if the string is fractional,
* `Long.class` if integral, or `null` if it
* is not a valid number.
*/
public static Type numberType(CharSequence s)
{
s=s.toString().trim();
boolean minus = false;
boolean decimal = false;
boolean digits = false;
int n=0;
for(; n < s.length(); n++)
{
char ch = s.charAt(n);
if (ch=='-')
{
if (minus || digits) return null;
minus=true;
continue;
}
if (ch=='.')
{
if (decimal) return null;
decimal=true;
continue;
}
if(Character.isDigit(ch))
{
digits=true;
continue;
}
return null;
}
if (!digits) return null;
return decimal ? Double.class : Long.class;
}
public static boolean isAsciiLetter(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
public static boolean isIdentifier(String s)
{
for(int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
if(i==0)
{
if(!isAsciiLetter(ch) && ch != '_') return false;
}
else
{
if(!isAsciiLetter(ch) &&
!Character.isDigit(ch) &&
ch != '_') return false;
}
}
return true;
}
public static boolean equals(String a, String b)
{
if(a==null || b==null) return a==b;
return a.equals(b);
}
/**
* Formats a floating-point number. Unlike Double.toString,
* omits the decimal point if this number is not fractional.
*
* @param d
* @return
*/
public static String formatSimpleDouble(double d)
{
int i = (int)d;
return i==d ? Integer.toString(i) : Double.toString(d);
}
/**
* Turns a string into a conforming string key, which is
* always lowercase and only contains letters, numbers, and
* hyphens.
*
* TODO: examples
*
* "Kirchäckerstraße" ==> "kirchaeckerstrasse"
*
* @param s
* @return
*/
public static String makeKey(String s)
{
StringBuffer buf = new StringBuffer();
s = stripAccents(s);
boolean needsHyphen = false;
for(int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
if(Character.isLetter(ch))
{
if(needsHyphen)
{
buf.append('-');
needsHyphen=false;
}
ch = Character.toLowerCase(ch);
buf.append(ch);
continue;
}
if(Character.isDigit(ch))
{
if(needsHyphen)
{
buf.append('-');
needsHyphen=false;
}
buf.append(ch);
continue;
}
if(buf.length() > 0) needsHyphen = true;
}
return buf.toString();
}
public static boolean isAscii(String s)
{
for(int i=0; i<s.length(); i++)
{
if(s.charAt(i) >= 128) return false;
}
return true;
}
public static String stripAccents(String original)
{
String s = Normalizer.normalize(original, Normalizer.Form.NFD);
// if(s.equals(original)) return original;
if (isAscii(s)) return original;
StringBuffer buf = new StringBuffer();
boolean uppercase = false;
for(int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
switch(ch)
{
case '\u0308':
buf.append(uppercase ? 'E' : 'e');
break;
case 'æ':
buf.append("ae");
break;
case 'Æ':
buf.append("AE");
break;
case 'œ':
buf.append("oe");
break;
case 'Œ':
buf.append("OE");
break;
case 'Þ':
buf.append("th");
break;
case 'ð':
buf.append("d");
break;
case 'ß':
buf.append("ss");
break;
default:
if(ch < 128)
{
buf.append(ch);
uppercase = Character.isUpperCase(ch);
}
break;
}
}
// TODO: leading/trailing dash, d'
return buf.toString();
}
public static int longestCommonSubstring(String a, String b)
{
int m = a.length();
int n = b.length();
int max = 0;
int[][] dp = new int[m][n];
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(a.charAt(i) == b.charAt(j))
{
if(i==0 || j==0)
{
dp[i][j]=1;
}
else
{
dp[i][j] = dp[i-1][j-1]+1;
}
if(max < dp[i][j]) max=dp[i][j];
}
}
}
return max;
}
// TODO: remove
public static <T> String join(String delimiter, Iterable<T> items)
{
StringJoiner joiner = new StringJoiner(delimiter);
for(T item: items) joiner.add(item==null ? "null" : item.toString());
return joiner.toString();
}
// TODO: remove
public static <T> String join(String delimiter, Iterable<T> items, Function<T, Object> formatter)
{
StringJoiner joiner = new StringJoiner(delimiter);
for(T item: items) joiner.add(String.valueOf(formatter.apply(item)));
return joiner.toString();
}
public static int indexOfAny(String s, String any)
{
for(int i=0; i<s.length(); i++)
{
if(any.indexOf(s.charAt(i)) >= 0) return i;
}
return -1;
}
public static int countChar(String s, char ch)
{
int count = 0;
for(int i=0; i<s.length(); i++)
{
if(s.charAt(i)==ch) count++;
}
return count;
}
public static String uppercaseFirst(String s)
{
if(s.isEmpty()) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
/**
* Escapes a string for JSON encoding.
*
* @param s The input string to be escaped.
* @return The escaped string. If no escaping was needed,
* returns the original string.
*/
public static String escapeForJson(String s)
{
// Check if any character needs escaping.
boolean needsEscaping = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == '"' || c == '\\' || c < ' ')
{
needsEscaping = true;
break;
}
}
// Return original string if no escaping needed
if (!needsEscaping) return s;
// Escape necessary characters
StringBuilder escaped = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
switch (c)
{
case '"':
escaped.append("\\\"");
break;
case '\\':
escaped.append("\\\\");
break;
case '/':
escaped.append("\\/");
break;
case '\b':
escaped.append("\\b");
break;
case '\f':
escaped.append("\\f");
break;
case '\n':
escaped.append("\\n");
break;
case '\r':
escaped.append("\\r");
break;
case '\t':
escaped.append("\\t");
break;
default:
if (c < ' ') // For other unprintable characters
{
escaped.append(String.format("\\u%04x", (int) c));
}
else
{
escaped.append(c);
}
break;
}
}
return escaped.toString();
}
/**
* Replaces unprintable/control characters (tab, line feed, etc.)
* in the input string with a space.
*
* @param s The input string to be processed.
* @return The processed string with unprintable characters replaced by spaces.
* If no unprintable characters were found, returns the original string.
*/
public static String cleanString(String s)
{
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c < ' ')
{
StringBuilder processed = new StringBuilder(s.length());
for (i = 0; i < s.length(); i++)
{
c = s.charAt(i);
processed.append(c < ' ' ? ' ' : c);
}
return processed.toString();
}
}
return s;
}
}