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