Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 157119013253e206b88eac9bcb0b46d9ae8f0221 (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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
 * Copyright (c) 2007-2013, 2015, 2016 Eike Stepper (Berlin, Germany) 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:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.util;

import org.eclipse.net4j.util.om.OMPlatform;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Various static helper methods for dealing with strings.
 *
 * @author Eike Stepper
 */
public final class StringUtil
{
  public static final String EMPTY = ""; //$NON-NLS-1$

  public static final String NL = OMPlatform.INSTANCE.getProperty("line.separator"); //$NON-NLS-1$

  private StringUtil()
  {
  }

  /**
   * @since 3.4
   */
  public static String create(char c, int length)
  {
    char[] chars = new char[length];
    Arrays.fill(chars, c);
    return new String(chars);
  }

  /**
   * @since 2.0
   */
  public static String formatException(Throwable t)
  {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream s = new PrintStream(baos);
    t.printStackTrace(s);
    return baos.toString();
  }

  public static String replace(String text, String[] find, String[] replace)
  {
    for (int i = 0; i < find.length; i++)
    {
      int end = 0;
      for (;;)
      {
        int start = text.indexOf(find[i], end);
        if (start == -1)
        {
          break;
        }

        end = start + find[i].length();
        text = text.substring(0, start) + replace[i] + text.substring(end);
      }
    }

    return text;
  }

  /**
   * @since 3.4
   */
  public static List<String> split(String text, String separators, String brackets)
  {
    List<String> result = new ArrayList<String>();

    StringBuilder builder = new StringBuilder();
    int length = text.length();
    int bracketLevel = 0;

    for (int i = 0; i < length; i++)
    {
      char c = text.charAt(i);

      if (bracketLevel == 0 && separators.indexOf(c) != -1)
      {
        result.add(builder.toString());
        builder.setLength(0);
      }
      else
      {
        builder.append(c);
      }

      if (brackets != null)
      {
        int bracket = brackets.indexOf(c);
        if (bracket != -1)
        {
          if ((bracket & 1) == 0)
          {
            // Opening bracket
            ++bracketLevel;
          }
          else
          {
            // Closing bracket
            --bracketLevel;
          }
        }
      }
    }

    result.add(builder.toString());
    return result;
  }

  public static String safe(String str)
  {
    return safe(str, EMPTY);
  }

  /**
   * @since 3.4
   */
  public static String safe(String str, String def)
  {
    if (str == null)
    {
      return def;
    }

    return str;
  }

  public static int compare(String s1, String s2)
  {
    if (s1 == null)
    {
      return s2 == null ? 0 : -1;
    }

    if (s2 == null)
    {
      return 1;
    }

    return s1.compareTo(s2);
  }

  /**
   * @since 3.1
   */
  public static boolean equalsUpperOrLowerCase(String s, String upperOrLowerCase)
  {
    if (s == null)
    {
      return upperOrLowerCase == null;
    }

    return s.equals(upperOrLowerCase.toLowerCase()) || s.equals(upperOrLowerCase.toUpperCase());
  }

  /**
   * @since 2.0
   */
  public static String capAll(String str)
  {
    if (str == null || str.length() == 0)
    {
      return str;
    }

    boolean inWhiteSpace = true;
    StringBuilder builder = new StringBuilder(str);
    for (int i = 0; i < builder.length(); i++)
    {
      char c = builder.charAt(i);
      boolean isWhiteSpace = Character.isWhitespace(c);
      if (!isWhiteSpace && inWhiteSpace)
      {
        builder.setCharAt(i, Character.toUpperCase(c));
      }

      inWhiteSpace = isWhiteSpace;
    }

    return builder.toString();
  }

  public static String cap(String str)
  {
    if (str == null || str.length() == 0)
    {
      return str;
    }

    char first = str.charAt(0);
    if (Character.isUpperCase(first))
    {
      return str;
    }

    if (str.length() == 1)
    {
      return str.toUpperCase();
    }

    StringBuilder builder = new StringBuilder(str);
    builder.setCharAt(0, Character.toUpperCase(first));
    return builder.toString();
  }

  /**
   * @since 2.0
   */
  public static String uncapAll(String str)
  {
    if (str == null || str.length() == 0)
    {
      return str;
    }

    boolean inWhiteSpace = true;
    StringBuilder builder = new StringBuilder(str);
    for (int i = 0; i < builder.length(); i++)
    {
      char c = builder.charAt(i);
      boolean isWhiteSpace = Character.isWhitespace(c);
      if (!isWhiteSpace && inWhiteSpace)
      {
        builder.setCharAt(i, Character.toLowerCase(c));
      }

      inWhiteSpace = isWhiteSpace;
    }

    return builder.toString();
  }

  public static String uncap(String str)
  {
    if (str == null || str.length() == 0)
    {
      return str;
    }

    char first = str.charAt(0);
    if (Character.isLowerCase(first))
    {
      return str;
    }

    if (str.length() == 1)
    {
      return str.toLowerCase();
    }

    StringBuilder builder = new StringBuilder(str);
    builder.setCharAt(0, Character.toLowerCase(first));
    return builder.toString();
  }

  public static int occurrences(String str, char c)
  {
    int count = 0;
    for (int i = 0; (i = str.indexOf(c, i)) != -1; ++i)
    {
      ++count;
    }

    return count;
  }

  public static int occurrences(String str, String c)
  {
    int count = 0;
    for (int i = 0; (i = str.indexOf(c, i)) != -1; i += c.length())
    {
      ++count;
    }

    return count;
  }

  /**
   * @since 3.8
   */
  public static String translate(String str, String from, String to)
  {
    int length = str == null ? 0 : str.length();
    if (length == 0)
    {
      return str;
    }

    int fromLength = from.length();
    int toLength = to.length();

    if (fromLength == 0)
    {
      return str;
    }

    if (fromLength > toLength)
    {
      throw new IllegalArgumentException("'from' is longer than 'to'");
    }

    StringBuilder builder = null;
    for (int i = 0; i < length; i++)
    {
      char c = str.charAt(i);

      int pos = from.indexOf(c);
      if (pos != -1)
      {
        c = to.charAt(pos);

        if (builder == null)
        {
          builder = new StringBuilder(str);
        }

        builder.setCharAt(i, c);
      }
    }

    if (builder == null)
    {
      return str;
    }

    return builder.toString();
  }

  public static boolean isEmpty(String str)
  {
    return ObjectUtil.isEmpty(str);
  }

  /**
   * Matches a string against a pattern.
   * <p>
   * Pattern description:
   * <ul>
   * <li><code>*</code> matches 0 or more characters
   * <li><code>?</code> matches a single character
   * <li><code>[...]</code> matches a set and/or range of characters
   * <li><code>\</code> escapes the following character
   * </ul>
   *
   * @since 2.0
   */
  public static boolean glob(String pattern, String string)
  {
    return glob(pattern, string, null);
  }

  /**
   * Matches a string against a pattern and fills an array with the sub-matches.
   * <p>
   * Pattern description:
   * <ul>
   * <li><code>*</code> matches 0 or more characters
   * <li><code>?</code> matches a single character
   * <li><code>[...]</code> matches a set and/or range of characters
   * <li><code>\</code> escapes the following character
   * </ul>
   *
   * @since 2.0
   */
  public static boolean glob(String pattern, String string, String[] subStrings)
  {
    return globRecurse(pattern, 0, string, 0, subStrings, 0);
  }

  private static boolean globRecurse(String pattern, int patternIndex, String string, int stringIndex, String[] subStrings, int subStringsIndex)
  {
    int patternLength = pattern.length();
    int stringLength = string.length();

    for (;;)
    {
      char patternChar = pattern.charAt(patternIndex);
      boolean endReached = stringIndex == stringLength;
      if (patternIndex == patternLength)
      {
        return endReached;
      }
      else if (endReached && patternChar != '*')
      {
        return false;
      }

      switch (patternChar)
      {
      case '*':
      {
        int startIndex = stringIndex;
        if (++patternIndex >= patternLength)
        {
          globRemember(string, startIndex, stringLength, subStrings, subStringsIndex);
          return true;
        }

        for (;;)
        {
          if (globRecurse(pattern, patternIndex, string, stringIndex, subStrings, subStringsIndex + 1))
          {
            globRemember(string, startIndex, stringIndex, subStrings, subStringsIndex);
            return true;
          }

          if (endReached)
          {
            return false;
          }

          ++stringIndex;
        }
      }

      case '?':
        ++patternIndex;
        globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++);
        break;

      case '[':
        try
        {
          ++patternIndex;
          char stringChar = string.charAt(stringIndex);
          char rangeStartChar = patternChar;

          while (true)
          {
            if (rangeStartChar == ']')
            {
              return false;
            }

            if (rangeStartChar == stringChar)
            {
              break;
            }

            ++patternIndex;
            char nextPatternChar = patternChar;
            if (nextPatternChar == '-')
            {
              ++patternIndex;
              char rangeEndChar = patternChar;
              if (rangeStartChar <= stringChar && stringChar <= rangeEndChar)
              {
                break;
              }

              ++patternIndex;
              nextPatternChar = patternChar;
            }

            rangeStartChar = nextPatternChar;
          }

          patternIndex = pattern.indexOf(']', patternIndex) + 1;
          if (patternIndex <= 0)
          {
            return false;
          }

          globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++);
        }
        catch (StringIndexOutOfBoundsException ex)
        {
          return false;
        }

        break;

      case '\\':
        if (++patternIndex >= patternLength)
        {
          return false;
        }

        //$FALL-THROUGH$
      default:
        if (patternChar++ != string.charAt(stringIndex++))
        {
          return false;
        }
      }
    }
  }

  private static void globRemember(String string, int start, int end, String[] subStrings, int subStringsIndex)
  {
    if (subStrings != null && subStringsIndex < subStrings.length)
    {
      subStrings[subStringsIndex] = string.substring(start, end);
    }
  }
}

Back to the top