001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static java.lang.Math.min;
020import static java.util.logging.Level.WARNING;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.VisibleForTesting;
024import java.util.logging.Logger;
025import javax.annotation.CheckForNull;
026import org.checkerframework.checker.nullness.qual.Nullable;
027
028/**
029 * Static utility methods pertaining to {@code String} or {@code CharSequence} instances.
030 *
031 * @author Kevin Bourrillion
032 * @since 3.0
033 */
034@GwtCompatible
035@ElementTypesAreNonnullByDefault
036public final class Strings {
037  private Strings() {}
038
039  /**
040   * Returns the given string if it is non-null; the empty string otherwise.
041   *
042   * @param string the string to test and possibly return
043   * @return {@code string} itself if it is non-null; {@code ""} if it is null
044   */
045  public static String nullToEmpty(@CheckForNull String string) {
046    return Platform.nullToEmpty(string);
047  }
048
049  /**
050   * Returns the given string if it is nonempty; {@code null} otherwise.
051   *
052   * @param string the string to test and possibly return
053   * @return {@code string} itself if it is nonempty; {@code null} if it is empty or null
054   */
055  @CheckForNull
056  public static String emptyToNull(@CheckForNull String string) {
057    return Platform.emptyToNull(string);
058  }
059
060  /**
061   * Returns {@code true} if the given string is null or is the empty string.
062   *
063   * <p>Consider normalizing your string references with {@link #nullToEmpty}. If you do, you can
064   * use {@link String#isEmpty()} instead of this method, and you won't need special null-safe forms
065   * of methods like {@link String#toUpperCase} either. Or, if you'd like to normalize "in the other
066   * direction," converting empty strings to {@code null}, you can use {@link #emptyToNull}.
067   *
068   * @param string a string reference to check
069   * @return {@code true} if the string is null or is the empty string
070   */
071  public static boolean isNullOrEmpty(@CheckForNull String string) {
072    return Platform.stringIsNullOrEmpty(string);
073  }
074
075  /**
076   * Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended
077   * with as many copies of {@code padChar} as are necessary to reach that length. For example,
078   *
079   * <ul>
080   *   <li>{@code padStart("7", 3, '0')} returns {@code "007"}
081   *   <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
082   * </ul>
083   *
084   * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities.
085   *
086   * @param string the string which should appear at the end of the result
087   * @param minLength the minimum length the resulting string must have. Can be zero or negative, in
088   *     which case the input string is always returned.
089   * @param padChar the character to insert at the beginning of the result until the minimum length
090   *     is reached
091   * @return the padded string
092   */
093  public static String padStart(String string, int minLength, char padChar) {
094    checkNotNull(string); // eager for GWT.
095    if (string.length() >= minLength) {
096      return string;
097    }
098    StringBuilder sb = new StringBuilder(minLength);
099    for (int i = string.length(); i < minLength; i++) {
100      sb.append(padChar);
101    }
102    sb.append(string);
103    return sb.toString();
104  }
105
106  /**
107   * Returns a string, of length at least {@code minLength}, consisting of {@code string} appended
108   * with as many copies of {@code padChar} as are necessary to reach that length. For example,
109   *
110   * <ul>
111   *   <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
112   *   <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
113   * </ul>
114   *
115   * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities.
116   *
117   * @param string the string which should appear at the beginning of the result
118   * @param minLength the minimum length the resulting string must have. Can be zero or negative, in
119   *     which case the input string is always returned.
120   * @param padChar the character to append to the end of the result until the minimum length is
121   *     reached
122   * @return the padded string
123   */
124  public static String padEnd(String string, int minLength, char padChar) {
125    checkNotNull(string); // eager for GWT.
126    if (string.length() >= minLength) {
127      return string;
128    }
129    StringBuilder sb = new StringBuilder(minLength);
130    sb.append(string);
131    for (int i = string.length(); i < minLength; i++) {
132      sb.append(padChar);
133    }
134    return sb.toString();
135  }
136
137  /**
138   * Returns a string consisting of a specific number of concatenated copies of an input string. For
139   * example, {@code repeat("hey", 3)} returns the string {@code "heyheyhey"}.
140   *
141   * @param string any non-null string
142   * @param count the number of times to repeat it; a nonnegative integer
143   * @return a string containing {@code string} repeated {@code count} times (the empty string if
144   *     {@code count} is zero)
145   * @throws IllegalArgumentException if {@code count} is negative
146   */
147  public static String repeat(String string, int count) {
148    checkNotNull(string); // eager for GWT.
149
150    if (count <= 1) {
151      checkArgument(count >= 0, "invalid count: %s", count);
152      return (count == 0) ? "" : string;
153    }
154
155    // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark
156    final int len = string.length();
157    final long longSize = (long) len * (long) count;
158    final int size = (int) longSize;
159    if (size != longSize) {
160      throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize);
161    }
162
163    final char[] array = new char[size];
164    string.getChars(0, len, array, 0);
165    int n;
166    for (n = len; n < size - n; n <<= 1) {
167      System.arraycopy(array, 0, array, n, n);
168    }
169    System.arraycopy(array, 0, array, n, size - n);
170    return new String(array);
171  }
172
173  /**
174   * Returns the longest string {@code prefix} such that {@code a.toString().startsWith(prefix) &&
175   * b.toString().startsWith(prefix)}, taking care not to split surrogate pairs. If {@code a} and
176   * {@code b} have no common prefix, returns the empty string.
177   *
178   * @since 11.0
179   */
180  public static String commonPrefix(CharSequence a, CharSequence b) {
181    checkNotNull(a);
182    checkNotNull(b);
183
184    int maxPrefixLength = min(a.length(), b.length());
185    int p = 0;
186    while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
187      p++;
188    }
189    if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
190      p--;
191    }
192    return a.subSequence(0, p).toString();
193  }
194
195  /**
196   * Returns the longest string {@code suffix} such that {@code a.toString().endsWith(suffix) &&
197   * b.toString().endsWith(suffix)}, taking care not to split surrogate pairs. If {@code a} and
198   * {@code b} have no common suffix, returns the empty string.
199   *
200   * @since 11.0
201   */
202  public static String commonSuffix(CharSequence a, CharSequence b) {
203    checkNotNull(a);
204    checkNotNull(b);
205
206    int maxSuffixLength = min(a.length(), b.length());
207    int s = 0;
208    while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) {
209      s++;
210    }
211    if (validSurrogatePairAt(a, a.length() - s - 1)
212        || validSurrogatePairAt(b, b.length() - s - 1)) {
213      s--;
214    }
215    return a.subSequence(a.length() - s, a.length()).toString();
216  }
217
218  /**
219   * True when a valid surrogate pair starts at the given {@code index} in the given {@code string}.
220   * Out-of-range indexes return false.
221   */
222  @VisibleForTesting
223  static boolean validSurrogatePairAt(CharSequence string, int index) {
224    return index >= 0
225        && index <= (string.length() - 2)
226        && Character.isHighSurrogate(string.charAt(index))
227        && Character.isLowSurrogate(string.charAt(index + 1));
228  }
229
230  /**
231   * Returns the given {@code template} string with each occurrence of {@code "%s"} replaced with
232   * the corresponding argument value from {@code args}; or, if the placeholder and argument counts
233   * do not match, returns a best-effort form of that string. Will not throw an exception under
234   * normal conditions.
235   *
236   * <p><b>Note:</b> For most string-formatting needs, use {@link String#format String.format},
237   * {@link java.io.PrintWriter#format PrintWriter.format}, and related methods. These support the
238   * full range of <a
239   * href="https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html#syntax">format
240   * specifiers</a>, and alert you to usage errors by throwing {@link
241   * java.util.IllegalFormatException}.
242   *
243   * <p>In certain cases, such as outputting debugging information or constructing a message to be
244   * used for another unchecked exception, an exception during string formatting would serve little
245   * purpose except to supplant the real information you were trying to provide. These are the cases
246   * this method is made for; it instead generates a best-effort string with all supplied argument
247   * values present. This method is also useful in environments such as GWT where {@code
248   * String.format} is not available. As an example, method implementations of the {@link
249   * Preconditions} class use this formatter, for both of the reasons just discussed.
250   *
251   * <p><b>Warning:</b> Only the exact two-character placeholder sequence {@code "%s"} is
252   * recognized.
253   *
254   * @param template a string containing zero or more {@code "%s"} placeholder sequences. {@code
255   *     null} is treated as the four-character string {@code "null"}.
256   * @param args the arguments to be substituted into the message template. The first argument
257   *     specified is substituted for the first occurrence of {@code "%s"} in the template, and so
258   *     forth. A {@code null} argument is converted to the four-character string {@code "null"};
259   *     non-null values are converted to strings using {@link Object#toString()}.
260   * @since 25.1
261   */
262  // TODO(diamondm) consider using Arrays.toString() for array parameters
263  public static String lenientFormat(
264      @CheckForNull String template, @CheckForNull @Nullable Object... args) {
265    template = String.valueOf(template); // null -> "null"
266
267    if (args == null) {
268      args = new Object[] {"(Object[])null"};
269    } else {
270      for (int i = 0; i < args.length; i++) {
271        args[i] = lenientToString(args[i]);
272      }
273    }
274
275    // start substituting the arguments into the '%s' placeholders
276    StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
277    int templateStart = 0;
278    int i = 0;
279    while (i < args.length) {
280      int placeholderStart = template.indexOf("%s", templateStart);
281      if (placeholderStart == -1) {
282        break;
283      }
284      builder.append(template, templateStart, placeholderStart);
285      builder.append(args[i++]);
286      templateStart = placeholderStart + 2;
287    }
288    builder.append(template, templateStart, template.length());
289
290    // if we run out of placeholders, append the extra args in square braces
291    if (i < args.length) {
292      builder.append(" [");
293      builder.append(args[i++]);
294      while (i < args.length) {
295        builder.append(", ");
296        builder.append(args[i++]);
297      }
298      builder.append(']');
299    }
300
301    return builder.toString();
302  }
303
304  private static String lenientToString(@CheckForNull Object o) {
305    if (o == null) {
306      return "null";
307    }
308    try {
309      return o.toString();
310    } catch (Exception e) {
311      // Default toString() behavior - see Object.toString()
312      String objectToString =
313          o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o));
314      // Logger is created inline with fixed name to avoid forcing Proguard to create another class.
315      Logger.getLogger("com.google.common.base.Strings")
316          .log(WARNING, "Exception during lenientFormat for " + objectToString, e);
317      return "<" + objectToString + " threw " + e.getClass().getName() + ">";
318    }
319  }
320}