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