1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.inputmethod.latin.common;
18
19import com.android.inputmethod.annotations.UsedForTesting;
20
21import java.util.ArrayList;
22import java.util.Arrays;
23import java.util.Locale;
24
25import javax.annotation.Nonnull;
26import javax.annotation.Nullable;
27
28public final class StringUtils {
29    public static final int CAPITALIZE_NONE = 0;  // No caps, or mixed case
30    public static final int CAPITALIZE_FIRST = 1; // First only
31    public static final int CAPITALIZE_ALL = 2;   // All caps
32
33    @Nonnull
34    private static final String EMPTY_STRING = "";
35
36    private static final char CHAR_LINE_FEED = 0X000A;
37    private static final char CHAR_VERTICAL_TAB = 0X000B;
38    private static final char CHAR_FORM_FEED = 0X000C;
39    private static final char CHAR_CARRIAGE_RETURN = 0X000D;
40    private static final char CHAR_NEXT_LINE = 0X0085;
41    private static final char CHAR_LINE_SEPARATOR = 0X2028;
42    private static final char CHAR_PARAGRAPH_SEPARATOR = 0X2029;
43
44    private StringUtils() {
45        // This utility class is not publicly instantiable.
46    }
47
48    // Taken from android.text.TextUtils. We are extensively using this method in many places,
49    // some of which don't have the android libraries available.
50    /**
51     * Returns true if the string is null or 0-length.
52     * @param str the string to be examined
53     * @return true if str is null or zero length
54     */
55    public static boolean isEmpty(@Nullable final CharSequence str) {
56        return (str == null || str.length() == 0);
57    }
58
59    // Taken from android.text.TextUtils to cut the dependency to the Android framework.
60    /**
61     * Returns a string containing the tokens joined by delimiters.
62     * @param delimiter the delimiter
63     * @param tokens an array objects to be joined. Strings will be formed from
64     *     the objects by calling object.toString().
65     */
66    @Nonnull
67    public static String join(@Nonnull final CharSequence delimiter,
68            @Nonnull final Iterable<?> tokens) {
69        final StringBuilder sb = new StringBuilder();
70        boolean firstTime = true;
71        for (final Object token: tokens) {
72            if (firstTime) {
73                firstTime = false;
74            } else {
75                sb.append(delimiter);
76            }
77            sb.append(token);
78        }
79        return sb.toString();
80    }
81
82    // Taken from android.text.TextUtils to cut the dependency to the Android framework.
83    /**
84     * Returns true if a and b are equal, including if they are both null.
85     * <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if
86     * both the arguments were instances of String.</i></p>
87     * @param a first CharSequence to check
88     * @param b second CharSequence to check
89     * @return true if a and b are equal
90     */
91    public static boolean equals(@Nullable final CharSequence a, @Nullable final CharSequence b) {
92        if (a == b) {
93            return true;
94        }
95        final int length;
96        if (a != null && b != null && (length = a.length()) == b.length()) {
97            if (a instanceof String && b instanceof String) {
98                return a.equals(b);
99            }
100            for (int i = 0; i < length; i++) {
101                if (a.charAt(i) != b.charAt(i)) {
102                    return false;
103                }
104            }
105            return true;
106        }
107        return false;
108    }
109
110    public static int codePointCount(@Nullable final CharSequence text) {
111        if (isEmpty(text)) {
112            return 0;
113        }
114        return Character.codePointCount(text, 0, text.length());
115    }
116
117    @Nonnull
118    public static String newSingleCodePointString(final int codePoint) {
119        if (Character.charCount(codePoint) == 1) {
120            // Optimization: avoid creating a temporary array for characters that are
121            // represented by a single char value
122            return String.valueOf((char) codePoint);
123        }
124        // For surrogate pair
125        return new String(Character.toChars(codePoint));
126    }
127
128    public static boolean containsInArray(@Nonnull final String text,
129            @Nonnull final String[] array) {
130        for (final String element : array) {
131            if (text.equals(element)) {
132                return true;
133            }
134        }
135        return false;
136    }
137
138    /**
139     * Comma-Splittable Text is similar to Comma-Separated Values (CSV) but has much simpler syntax.
140     * Unlike CSV, Comma-Splittable Text has no escaping mechanism, so that the text can't contain
141     * a comma character in it.
142     */
143    @Nonnull
144    private static final String SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT = ",";
145
146    public static boolean containsInCommaSplittableText(@Nonnull final String text,
147            @Nullable final String extraValues) {
148        if (isEmpty(extraValues)) {
149            return false;
150        }
151        return containsInArray(text, extraValues.split(SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT));
152    }
153
154    @Nonnull
155    public static String removeFromCommaSplittableTextIfExists(@Nonnull final String text,
156            @Nullable final String extraValues) {
157        if (isEmpty(extraValues)) {
158            return EMPTY_STRING;
159        }
160        final String[] elements = extraValues.split(SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT);
161        if (!containsInArray(text, elements)) {
162            return extraValues;
163        }
164        final ArrayList<String> result = new ArrayList<>(elements.length - 1);
165        for (final String element : elements) {
166            if (!text.equals(element)) {
167                result.add(element);
168            }
169        }
170        return join(SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT, result);
171    }
172
173    /**
174     * Remove duplicates from an array of strings.
175     *
176     * This method will always keep the first occurrence of all strings at their position
177     * in the array, removing the subsequent ones.
178     */
179    public static void removeDupes(@Nonnull final ArrayList<String> suggestions) {
180        if (suggestions.size() < 2) {
181            return;
182        }
183        int i = 1;
184        // Don't cache suggestions.size(), since we may be removing items
185        while (i < suggestions.size()) {
186            final String cur = suggestions.get(i);
187            // Compare each suggestion with each previous suggestion
188            for (int j = 0; j < i; j++) {
189                final String previous = suggestions.get(j);
190                if (equals(cur, previous)) {
191                    suggestions.remove(i);
192                    i--;
193                    break;
194                }
195            }
196            i++;
197        }
198    }
199
200    @Nonnull
201    public static String capitalizeFirstCodePoint(@Nonnull final String s,
202            @Nonnull final Locale locale) {
203        if (s.length() <= 1) {
204            return s.toUpperCase(getLocaleUsedForToTitleCase(locale));
205        }
206        // Please refer to the comment below in
207        // {@link #capitalizeFirstAndDowncaseRest(String,Locale)} as this has the same shortcomings
208        final int cutoff = s.offsetByCodePoints(0, 1);
209        return s.substring(0, cutoff).toUpperCase(getLocaleUsedForToTitleCase(locale))
210                + s.substring(cutoff);
211    }
212
213    @Nonnull
214    public static String capitalizeFirstAndDowncaseRest(@Nonnull final String s,
215            @Nonnull final Locale locale) {
216        if (s.length() <= 1) {
217            return s.toUpperCase(getLocaleUsedForToTitleCase(locale));
218        }
219        // TODO: fix the bugs below
220        // - It does not work for Serbian, because it fails to account for the "lj" character,
221        // which should be "Lj" in title case and "LJ" in upper case.
222        // - It does not work for Dutch, because it fails to account for the "ij" digraph when it's
223        // written as two separate code points. They are two different characters but both should
224        // be capitalized as "IJ" as if they were a single letter in most words (not all). If the
225        // unicode char for the ligature is used however, it works.
226        final int cutoff = s.offsetByCodePoints(0, 1);
227        return s.substring(0, cutoff).toUpperCase(getLocaleUsedForToTitleCase(locale))
228                + s.substring(cutoff).toLowerCase(locale);
229    }
230
231    @Nonnull
232    public static int[] toCodePointArray(@Nonnull final CharSequence charSequence) {
233        return toCodePointArray(charSequence, 0, charSequence.length());
234    }
235
236    @Nonnull
237    private static final int[] EMPTY_CODEPOINTS = {};
238
239    /**
240     * Converts a range of a string to an array of code points.
241     * @param charSequence the source string.
242     * @param startIndex the start index inside the string in java chars, inclusive.
243     * @param endIndex the end index inside the string in java chars, exclusive.
244     * @return a new array of code points. At most endIndex - startIndex, but possibly less.
245     */
246    @Nonnull
247    public static int[] toCodePointArray(@Nonnull final CharSequence charSequence,
248            final int startIndex, final int endIndex) {
249        final int length = charSequence.length();
250        if (length <= 0) {
251            return EMPTY_CODEPOINTS;
252        }
253        final int[] codePoints =
254                new int[Character.codePointCount(charSequence, startIndex, endIndex)];
255        copyCodePointsAndReturnCodePointCount(codePoints, charSequence, startIndex, endIndex,
256                false /* downCase */);
257        return codePoints;
258    }
259
260    /**
261     * Copies the codepoints in a CharSequence to an int array.
262     *
263     * This method assumes there is enough space in the array to store the code points. The size
264     * can be measured with Character#codePointCount(CharSequence, int, int) before passing to this
265     * method. If the int array is too small, an ArrayIndexOutOfBoundsException will be thrown.
266     * Also, this method makes no effort to be thread-safe. Do not modify the CharSequence while
267     * this method is running, or the behavior is undefined.
268     * This method can optionally downcase code points before copying them, but it pays no attention
269     * to locale while doing so.
270     *
271     * @param destination the int array.
272     * @param charSequence the CharSequence.
273     * @param startIndex the start index inside the string in java chars, inclusive.
274     * @param endIndex the end index inside the string in java chars, exclusive.
275     * @param downCase if this is true, code points will be downcased before being copied.
276     * @return the number of copied code points.
277     */
278    public static int copyCodePointsAndReturnCodePointCount(@Nonnull final int[] destination,
279            @Nonnull final CharSequence charSequence, final int startIndex, final int endIndex,
280            final boolean downCase) {
281        int destIndex = 0;
282        for (int index = startIndex; index < endIndex;
283                index = Character.offsetByCodePoints(charSequence, index, 1)) {
284            final int codePoint = Character.codePointAt(charSequence, index);
285            // TODO: stop using this, as it's not aware of the locale and does not always do
286            // the right thing.
287            destination[destIndex] = downCase ? Character.toLowerCase(codePoint) : codePoint;
288            destIndex++;
289        }
290        return destIndex;
291    }
292
293    @Nonnull
294    public static int[] toSortedCodePointArray(@Nonnull final String string) {
295        final int[] codePoints = toCodePointArray(string);
296        Arrays.sort(codePoints);
297        return codePoints;
298    }
299
300    /**
301     * Construct a String from a code point array
302     *
303     * @param codePoints a code point array that is null terminated when its logical length is
304     * shorter than the array length.
305     * @return a string constructed from the code point array.
306     */
307    @Nonnull
308    public static String getStringFromNullTerminatedCodePointArray(
309            @Nonnull final int[] codePoints) {
310        int stringLength = codePoints.length;
311        for (int i = 0; i < codePoints.length; i++) {
312            if (codePoints[i] == 0) {
313                stringLength = i;
314                break;
315            }
316        }
317        return new String(codePoints, 0 /* offset */, stringLength);
318    }
319
320    // This method assumes the text is not null. For the empty string, it returns CAPITALIZE_NONE.
321    public static int getCapitalizationType(@Nonnull final String text) {
322        // If the first char is not uppercase, then the word is either all lower case or
323        // camel case, and in either case we return CAPITALIZE_NONE.
324        final int len = text.length();
325        int index = 0;
326        for (; index < len; index = text.offsetByCodePoints(index, 1)) {
327            if (Character.isLetter(text.codePointAt(index))) {
328                break;
329            }
330        }
331        if (index == len) return CAPITALIZE_NONE;
332        if (!Character.isUpperCase(text.codePointAt(index))) {
333            return CAPITALIZE_NONE;
334        }
335        int capsCount = 1;
336        int letterCount = 1;
337        for (index = text.offsetByCodePoints(index, 1); index < len;
338                index = text.offsetByCodePoints(index, 1)) {
339            if (1 != capsCount && letterCount != capsCount) break;
340            final int codePoint = text.codePointAt(index);
341            if (Character.isUpperCase(codePoint)) {
342                ++capsCount;
343                ++letterCount;
344            } else if (Character.isLetter(codePoint)) {
345                // We need to discount non-letters since they may not be upper-case, but may
346                // still be part of a word (e.g. single quote or dash, as in "IT'S" or "FULL-TIME")
347                ++letterCount;
348            }
349        }
350        // We know the first char is upper case. So we want to test if either every letter other
351        // than the first is lower case, or if they are all upper case. If the string is exactly
352        // one char long, then we will arrive here with letterCount 1, and this is correct, too.
353        if (1 == capsCount) return CAPITALIZE_FIRST;
354        return (letterCount == capsCount ? CAPITALIZE_ALL : CAPITALIZE_NONE);
355    }
356
357    public static boolean isIdenticalAfterUpcase(@Nonnull final String text) {
358        final int length = text.length();
359        int i = 0;
360        while (i < length) {
361            final int codePoint = text.codePointAt(i);
362            if (Character.isLetter(codePoint) && !Character.isUpperCase(codePoint)) {
363                return false;
364            }
365            i += Character.charCount(codePoint);
366        }
367        return true;
368    }
369
370    public static boolean isIdenticalAfterDowncase(@Nonnull final String text) {
371        final int length = text.length();
372        int i = 0;
373        while (i < length) {
374            final int codePoint = text.codePointAt(i);
375            if (Character.isLetter(codePoint) && !Character.isLowerCase(codePoint)) {
376                return false;
377            }
378            i += Character.charCount(codePoint);
379        }
380        return true;
381    }
382
383    public static boolean isIdenticalAfterCapitalizeEachWord(@Nonnull final String text,
384            @Nonnull final int[] sortedSeparators) {
385        boolean needsCapsNext = true;
386        final int len = text.length();
387        for (int i = 0; i < len; i = text.offsetByCodePoints(i, 1)) {
388            final int codePoint = text.codePointAt(i);
389            if (Character.isLetter(codePoint)) {
390                if ((needsCapsNext && !Character.isUpperCase(codePoint))
391                        || (!needsCapsNext && !Character.isLowerCase(codePoint))) {
392                    return false;
393                }
394            }
395            // We need a capital letter next if this is a separator.
396            needsCapsNext = (Arrays.binarySearch(sortedSeparators, codePoint) >= 0);
397        }
398        return true;
399    }
400
401    // TODO: like capitalizeFirst*, this does not work perfectly for Dutch because of the IJ digraph
402    // which should be capitalized together in *some* cases.
403    @Nonnull
404    public static String capitalizeEachWord(@Nonnull final String text,
405            @Nonnull final int[] sortedSeparators, @Nonnull final Locale locale) {
406        final StringBuilder builder = new StringBuilder();
407        boolean needsCapsNext = true;
408        final int len = text.length();
409        for (int i = 0; i < len; i = text.offsetByCodePoints(i, 1)) {
410            final String nextChar = text.substring(i, text.offsetByCodePoints(i, 1));
411            if (needsCapsNext) {
412                builder.append(nextChar.toUpperCase(locale));
413            } else {
414                builder.append(nextChar.toLowerCase(locale));
415            }
416            // We need a capital letter next if this is a separator.
417            needsCapsNext = (Arrays.binarySearch(sortedSeparators, nextChar.codePointAt(0)) >= 0);
418        }
419        return builder.toString();
420    }
421
422    /**
423     * Approximates whether the text before the cursor looks like a URL.
424     *
425     * This is not foolproof, but it should work well in the practice.
426     * Essentially it walks backward from the cursor until it finds something that's not a letter,
427     * digit, or common URL symbol like underscore. If it hasn't found a period yet, then it
428     * does not look like a URL.
429     * If the text:
430     * - starts with www and contains a period
431     * - starts with a slash preceded by either a slash, whitespace, or start-of-string
432     * Then it looks like a URL and we return true. Otherwise, we return false.
433     *
434     * Note: this method is called quite often, and should be fast.
435     *
436     * TODO: This will return that "abc./def" and ".abc/def" look like URLs to keep down the
437     * code complexity, but ideally it should not. It's acceptable for now.
438     */
439    public static boolean lastPartLooksLikeURL(@Nonnull final CharSequence text) {
440        int i = text.length();
441        if (0 == i) {
442            return false;
443        }
444        int wCount = 0;
445        int slashCount = 0;
446        boolean hasSlash = false;
447        boolean hasPeriod = false;
448        int codePoint = 0;
449        while (i > 0) {
450            codePoint = Character.codePointBefore(text, i);
451            if (codePoint < Constants.CODE_PERIOD || codePoint > 'z') {
452                // Handwavy heuristic to see if that's a URL character. Anything between period
453                // and z. This includes all lower- and upper-case ascii letters, period,
454                // underscore, arrobase, question mark, equal sign. It excludes spaces, exclamation
455                // marks, double quotes...
456                // Anything that's not a URL-like character causes us to break from here and
457                // evaluate normally.
458                break;
459            }
460            if (Constants.CODE_PERIOD == codePoint) {
461                hasPeriod = true;
462            }
463            if (Constants.CODE_SLASH == codePoint) {
464                hasSlash = true;
465                if (2 == ++slashCount) {
466                    return true;
467                }
468            } else {
469                slashCount = 0;
470            }
471            if ('w' == codePoint) {
472                ++wCount;
473            } else {
474                wCount = 0;
475            }
476            i = Character.offsetByCodePoints(text, i, -1);
477        }
478        // End of the text run.
479        // If it starts with www and includes a period, then it looks like a URL.
480        if (wCount >= 3 && hasPeriod) {
481            return true;
482        }
483        // If it starts with a slash, and the code point before is whitespace, it looks like an URL.
484        if (1 == slashCount && (0 == i || Character.isWhitespace(codePoint))) {
485            return true;
486        }
487        // If it has both a period and a slash, it looks like an URL.
488        if (hasPeriod && hasSlash) {
489            return true;
490        }
491        // Otherwise, it doesn't look like an URL.
492        return false;
493    }
494
495    /**
496     * Examines the string and returns whether we're inside a double quote.
497     *
498     * This is used to decide whether we should put an automatic space before or after a double
499     * quote character. If we're inside a quotation, then we want to close it, so we want a space
500     * after and not before. Otherwise, we want to open the quotation, so we want a space before
501     * and not after. Exception: after a digit, we never want a space because the "inch" or
502     * "minutes" use cases is dominant after digits.
503     * In the practice, we determine whether we are in a quotation or not by finding the previous
504     * double quote character, and looking at whether it's followed by whitespace. If so, that
505     * was a closing quotation mark, so we're not inside a double quote. If it's not followed
506     * by whitespace, then it was an opening quotation mark, and we're inside a quotation.
507     *
508     * @param text the text to examine.
509     * @return whether we're inside a double quote.
510     */
511    public static boolean isInsideDoubleQuoteOrAfterDigit(@Nonnull final CharSequence text) {
512        int i = text.length();
513        if (0 == i) {
514            return false;
515        }
516        int codePoint = Character.codePointBefore(text, i);
517        if (Character.isDigit(codePoint)) {
518            return true;
519        }
520        int prevCodePoint = 0;
521        while (i > 0) {
522            codePoint = Character.codePointBefore(text, i);
523            if (Constants.CODE_DOUBLE_QUOTE == codePoint) {
524                // If we see a double quote followed by whitespace, then that
525                // was a closing quote.
526                if (Character.isWhitespace(prevCodePoint)) {
527                    return false;
528                }
529            }
530            if (Character.isWhitespace(codePoint) && Constants.CODE_DOUBLE_QUOTE == prevCodePoint) {
531                // If we see a double quote preceded by whitespace, then that
532                // was an opening quote. No need to continue seeking.
533                return true;
534            }
535            i -= Character.charCount(codePoint);
536            prevCodePoint = codePoint;
537        }
538        // We reached the start of text. If the first char is a double quote, then we're inside
539        // a double quote. Otherwise we're not.
540        return Constants.CODE_DOUBLE_QUOTE == codePoint;
541    }
542
543    public static boolean isEmptyStringOrWhiteSpaces(@Nonnull final String s) {
544        final int N = codePointCount(s);
545        for (int i = 0; i < N; ++i) {
546            if (!Character.isWhitespace(s.codePointAt(i))) {
547                return false;
548            }
549        }
550        return true;
551    }
552
553    @UsedForTesting
554    @Nonnull
555    public static String byteArrayToHexString(@Nullable final byte[] bytes) {
556        if (bytes == null || bytes.length == 0) {
557            return EMPTY_STRING;
558        }
559        final StringBuilder sb = new StringBuilder();
560        for (final byte b : bytes) {
561            sb.append(String.format("%02x", b & 0xff));
562        }
563        return sb.toString();
564    }
565
566    /**
567     * Convert hex string to byte array. The string length must be an even number.
568     */
569    @UsedForTesting
570    @Nullable
571    public static byte[] hexStringToByteArray(@Nullable final String hexString) {
572        if (isEmpty(hexString)) {
573            return null;
574        }
575        final int N = hexString.length();
576        if (N % 2 != 0) {
577            throw new NumberFormatException("Input hex string length must be an even number."
578                    + " Length = " + N);
579        }
580        final byte[] bytes = new byte[N / 2];
581        for (int i = 0; i < N; i += 2) {
582            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
583                    + Character.digit(hexString.charAt(i + 1), 16));
584        }
585        return bytes;
586    }
587
588    private static final String LANGUAGE_GREEK = "el";
589
590    @Nonnull
591    private static Locale getLocaleUsedForToTitleCase(@Nonnull final Locale locale) {
592        // In Greek locale {@link String#toUpperCase(Locale)} eliminates accents from its result.
593        // In order to get accented upper case letter, {@link Locale#ROOT} should be used.
594        if (LANGUAGE_GREEK.equals(locale.getLanguage())) {
595            return Locale.ROOT;
596        }
597        return locale;
598    }
599
600    @Nullable
601    public static String toTitleCaseOfKeyLabel(@Nullable final String label,
602            @Nonnull final Locale locale) {
603        if (label == null) {
604            return label;
605        }
606        return label.toUpperCase(getLocaleUsedForToTitleCase(locale));
607    }
608
609    public static int toTitleCaseOfKeyCode(final int code, @Nonnull final Locale locale) {
610        if (!Constants.isLetterCode(code)) {
611            return code;
612        }
613        final String label = newSingleCodePointString(code);
614        final String titleCaseLabel = toTitleCaseOfKeyLabel(label, locale);
615        return codePointCount(titleCaseLabel) == 1
616                ? titleCaseLabel.codePointAt(0) : Constants.CODE_UNSPECIFIED;
617    }
618
619    public static int getTrailingSingleQuotesCount(@Nonnull final CharSequence charSequence) {
620        final int lastIndex = charSequence.length() - 1;
621        int i = lastIndex;
622        while (i >= 0 && charSequence.charAt(i) == Constants.CODE_SINGLE_QUOTE) {
623            --i;
624        }
625        return lastIndex - i;
626    }
627
628    @UsedForTesting
629    public static class Stringizer<E> {
630        @Nonnull
631        private static final String[] EMPTY_STRING_ARRAY = new String[0];
632
633        @UsedForTesting
634        @Nonnull
635        public String stringize(@Nullable final E element) {
636            if (element == null) {
637                return "null";
638            }
639            return element.toString();
640        }
641
642        @UsedForTesting
643        @Nonnull
644        public final String join(@Nullable final E[] array) {
645            return joinStringArray(toStringArray(array), null /* delimiter */);
646        }
647
648        @UsedForTesting
649        public final String join(@Nullable final E[] array, @Nullable final String delimiter) {
650            return joinStringArray(toStringArray(array), delimiter);
651        }
652
653        @Nonnull
654        protected String[] toStringArray(@Nullable final E[] array) {
655            if (array == null) {
656                return EMPTY_STRING_ARRAY;
657            }
658            final String[] stringArray = new String[array.length];
659            for (int index = 0; index < array.length; index++) {
660                stringArray[index] = stringize(array[index]);
661            }
662            return stringArray;
663        }
664
665        @Nonnull
666        protected String joinStringArray(@Nonnull final String[] stringArray,
667                @Nullable final String delimiter) {
668            if (delimiter == null) {
669                return Arrays.toString(stringArray);
670            }
671            final StringBuilder sb = new StringBuilder();
672            for (int index = 0; index < stringArray.length; index++) {
673                sb.append(index == 0 ? "[" : delimiter);
674                sb.append(stringArray[index]);
675            }
676            return sb + "]";
677        }
678    }
679
680    /**
681     * Returns whether the last composed word contains line-breaking character (e.g. CR or LF).
682     * @param text the text to be examined.
683     * @return {@code true} if the last composed word contains line-breaking separator.
684     */
685    public static boolean hasLineBreakCharacter(@Nullable final String text) {
686        if (isEmpty(text)) {
687            return false;
688        }
689        for (int i = text.length() - 1; i >= 0; --i) {
690            final char c = text.charAt(i);
691            switch (c) {
692                case CHAR_LINE_FEED:
693                case CHAR_VERTICAL_TAB:
694                case CHAR_FORM_FEED:
695                case CHAR_CARRIAGE_RETURN:
696                case CHAR_NEXT_LINE:
697                case CHAR_LINE_SEPARATOR:
698                case CHAR_PARAGRAPH_SEPARATOR:
699                    return true;
700            }
701        }
702        return false;
703    }
704}
705