001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.base;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021
022import com.google.common.annotations.GwtCompatible;
023
024import java.util.Formatter;
025
026import javax.annotation.Nullable;
027
028/**
029 * Static utility methods pertaining to {@code String} or {@code CharSequence}
030 * instances.
031 *
032 * @author Kevin Bourrillion
033 * @since 3
034 */
035@GwtCompatible
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(@Nullable String string) {
046    return (string == null) ? "" : 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
054   *     empty or null
055   */
056  public static @Nullable String emptyToNull(@Nullable String string) {
057    return isNullOrEmpty(string) ? null : 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}.
064   * If you do, you can use {@link String#isEmpty()} instead of this
065   * method, and you won't need special null-safe forms of methods like {@link
066   * String#toUpperCase} either. Or, if you'd like to normalize "in the other
067   * direction," converting empty strings to {@code null}, you can use {@link
068   * #emptyToNull}.
069   *
070   * @param string a string reference to check
071   * @return {@code true} if the string is null or is the empty string
072   */
073  public static boolean isNullOrEmpty(@Nullable String string) {
074    return string == null || string.length() == 0; // string.isEmpty() in Java 6
075  }
076
077  /**
078   * Returns a string, of length at least {@code minLength}, consisting of
079   * {@code string} prepended with as many copies of {@code padChar} as are
080   * necessary to reach that length. For example,
081   *
082   * <ul>
083   * <li>{@code padStart("7", 3, '0')} returns {@code "007"}
084   * <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
085   * </ul>
086   *
087   * <p>See {@link Formatter} for a richer set of formatting capabilities.
088   *
089   * @param string the string which should appear at the end of the result
090   * @param minLength the minimum length the resulting string must have. Can be
091   *     zero or negative, in which case the input string is always returned.
092   * @param padChar the character to insert at the beginning of the result until
093   *     the minimum length is reached
094   * @return the padded string
095   */
096  public static String padStart(String string, int minLength, char padChar) {
097    checkNotNull(string);  // eager for GWT.
098    if (string.length() >= minLength) {
099      return string;
100    }
101    StringBuilder sb = new StringBuilder(minLength);
102    for (int i = string.length(); i < minLength; i++) {
103      sb.append(padChar);
104    }
105    sb.append(string);
106    return sb.toString();
107  }
108
109  /**
110   * Returns a string, of length at least {@code minLength}, consisting of
111   * {@code string} appended with as many copies of {@code padChar} as are
112   * necessary to reach that length. For example,
113   *
114   * <ul>
115   * <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
116   * <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
117   * </ul>
118   *
119   * <p>See {@link Formatter} for a richer set of formatting capabilities.
120   *
121   * @param string the string which should appear at the beginning of the result
122   * @param minLength the minimum length the resulting string must have. Can be
123   *     zero or negative, in which case the input string is always returned.
124   * @param padChar the character to append to the end of the result until the
125   *     minimum length is reached
126   * @return the padded string
127   */
128  public static String padEnd(String string, int minLength, char padChar) {
129    checkNotNull(string);  // eager for GWT.
130    if (string.length() >= minLength) {
131      return string;
132    }
133    StringBuilder sb = new StringBuilder(minLength);
134    sb.append(string);
135    for (int i = string.length(); i < minLength; i++) {
136      sb.append(padChar);
137    }
138    return sb.toString();
139  }
140
141  /**
142   * Returns a string consisting of a specific number of concatenated copies of
143   * an input string. For example, {@code repeat("hey", 3)} returns the string
144   * {@code "heyheyhey"}.
145   *
146   * @param string any non-null string
147   * @param count the number of times to repeat it; a nonnegative integer
148   * @return a string containing {@code string} repeated {@code count} times
149   *     (the empty string if {@code count} is zero)
150   * @throws IllegalArgumentException if {@code count} is negative
151   */
152  public static String repeat(String string, int count) {
153    checkNotNull(string);  // eager for GWT.
154    checkArgument(count >= 0, "invalid count: %s", count);
155
156    // If this multiplication overflows, a NegativeArraySizeException or
157    // OutOfMemoryError is not far behind
158    StringBuilder builder = new StringBuilder(string.length() * count);
159    for (int i = 0; i < count; i++) {
160      builder.append(string);
161    }
162    return builder.toString();
163  }
164}
165