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.lang.System.arraycopy; 021import static java.util.logging.Level.WARNING; 022 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.VisibleForTesting; 025import com.google.errorprone.annotations.InlineMe; 026import com.google.errorprone.annotations.InlineMeValidationDisabled; 027import java.util.logging.Logger; 028import org.jspecify.annotations.Nullable; 029 030/** 031 * Static utility methods pertaining to {@code String} or {@code CharSequence} instances. 032 * 033 * @author Kevin Bourrillion 034 * @since 3.0 035 */ 036@GwtCompatible 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(@Nullable 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 public static @Nullable String emptyToNull(@Nullable 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(@Nullable 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 * <p><b>Java 11+ users and Android users:</b> use {@code string.repeat(count)} instead. 142 * 143 * @param string any non-null string 144 * @param count the number of times to repeat it; a nonnegative integer 145 * @return a string containing {@code string} repeated {@code count} times (the empty string if 146 * {@code count} is zero) 147 * @throws IllegalArgumentException if {@code count} is negative 148 */ 149 @InlineMe(replacement = "string.repeat(count)") 150 @InlineMeValidationDisabled("Java 11+ API only") 151 public static String repeat(String string, int count) { 152 checkNotNull(string); // eager for GWT. 153 154 if (count <= 1) { 155 checkArgument(count >= 0, "invalid count: %s", count); 156 return (count == 0) ? "" : string; 157 } 158 159 // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark 160 int len = string.length(); 161 long longSize = (long) len * (long) count; 162 int size = (int) longSize; 163 if (size != longSize) { 164 throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); 165 } 166 167 char[] array = new char[size]; 168 string.getChars(0, len, array, 0); 169 int n; 170 for (n = len; n < size - n; n <<= 1) { 171 arraycopy(array, 0, array, n, n); 172 } 173 arraycopy(array, 0, array, n, size - n); 174 return new String(array); 175 } 176 177 /** 178 * Returns the longest string {@code prefix} such that {@code a.toString().startsWith(prefix) && 179 * b.toString().startsWith(prefix)}, taking care not to split surrogate pairs. If {@code a} and 180 * {@code b} have no common prefix, returns the empty string. 181 * 182 * @since 11.0 183 */ 184 public static String commonPrefix(CharSequence a, CharSequence b) { 185 checkNotNull(a); 186 checkNotNull(b); 187 188 int maxPrefixLength = min(a.length(), b.length()); 189 int p = 0; 190 while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) { 191 p++; 192 } 193 if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) { 194 p--; 195 } 196 return a.subSequence(0, p).toString(); 197 } 198 199 /** 200 * Returns the longest string {@code suffix} such that {@code a.toString().endsWith(suffix) && 201 * b.toString().endsWith(suffix)}, taking care not to split surrogate pairs. If {@code a} and 202 * {@code b} have no common suffix, returns the empty string. 203 * 204 * @since 11.0 205 */ 206 public static String commonSuffix(CharSequence a, CharSequence b) { 207 checkNotNull(a); 208 checkNotNull(b); 209 210 int maxSuffixLength = min(a.length(), b.length()); 211 int s = 0; 212 while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) { 213 s++; 214 } 215 if (validSurrogatePairAt(a, a.length() - s - 1) 216 || validSurrogatePairAt(b, b.length() - s - 1)) { 217 s--; 218 } 219 return a.subSequence(a.length() - s, a.length()).toString(); 220 } 221 222 /** 223 * True when a valid surrogate pair starts at the given {@code index} in the given {@code string}. 224 * Out-of-range indexes return false. 225 */ 226 @VisibleForTesting 227 static boolean validSurrogatePairAt(CharSequence string, int index) { 228 return index >= 0 229 && index <= (string.length() - 2) 230 && Character.isHighSurrogate(string.charAt(index)) 231 && Character.isLowSurrogate(string.charAt(index + 1)); 232 } 233 234 /** 235 * Returns the given {@code template} string with each occurrence of {@code "%s"} replaced with 236 * the corresponding argument value from {@code args}; or, if the placeholder and argument counts 237 * do not match, returns a best-effort form of that string. Will not throw an exception under 238 * normal conditions. 239 * 240 * <p><b>Note:</b> For most string-formatting needs, use {@link String#format String.format}, 241 * {@link java.io.PrintWriter#format PrintWriter.format}, and related methods. These support the 242 * full range of {@linkplain java.util.Formatter##syntax format specifiers}, and alert you to 243 * usage errors by throwing {@link java.util.IllegalFormatException}. 244 * 245 * <p>In certain cases, such as outputting debugging information or constructing a message to be 246 * used for another unchecked exception, an exception during string formatting would serve little 247 * purpose except to supplant the real information you were trying to provide. These are the cases 248 * this method is made for; it instead generates a best-effort string with all supplied argument 249 * values present. This method is also useful in environments such as GWT where {@code 250 * String.format} is not available. As an example, method implementations of the {@link 251 * Preconditions} class use this formatter, for both of the reasons just discussed. 252 * 253 * <p><b>Warning:</b> Only the exact two-character placeholder sequence {@code "%s"} is 254 * recognized. 255 * 256 * @param template a string containing zero or more {@code "%s"} placeholder sequences. {@code 257 * null} is treated as the four-character string {@code "null"}. 258 * @param args the arguments to be substituted into the message template. The first argument 259 * specified is substituted for the first occurrence of {@code "%s"} in the template, and so 260 * forth. A {@code null} argument is converted to the four-character string {@code "null"}; 261 * non-null values are converted to strings using {@link Object#toString()}. 262 * @since 25.1 263 */ 264 // TODO(b/136042644): consider using Arrays.toString() for array parameters 265 public static String lenientFormat( 266 @Nullable String template, @Nullable Object @Nullable ... args) { 267 template = String.valueOf(template); // null -> "null" 268 269 if (args == null) { 270 args = new Object[] {"(Object[])null"}; 271 } 272 273 // start substituting the arguments into the '%s' placeholders 274 StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); 275 int templateStart = 0; 276 int i = 0; 277 while (i < args.length) { 278 int placeholderStart = template.indexOf("%s", templateStart); 279 if (placeholderStart == -1) { 280 break; 281 } 282 builder.append(template, templateStart, placeholderStart); 283 builder.append(lenientToString(args[i++])); 284 templateStart = placeholderStart + 2; 285 } 286 builder.append(template, templateStart, template.length()); 287 288 // if we run out of placeholders, append the extra args in square brackets 289 if (i < args.length) { 290 String prefix = " ["; 291 for (; i < args.length; i++) { 292 builder.append(prefix); 293 builder.append(lenientToString(args[i])); 294 prefix = ", "; 295 } 296 builder.append(']'); 297 } 298 299 return builder.toString(); 300 } 301 302 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 303 private static String lenientToString(@Nullable Object o) { 304 if (o == null) { 305 return "null"; 306 } 307 try { 308 return o.toString(); 309 } catch (Exception e) { // sneaky checked exception 310 // Default toString() behavior - see Object.toString() 311 String objectToString = 312 o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); 313 // Logger is created inline with fixed name to avoid forcing Proguard to create another class. 314 Logger.getLogger("com.google.common.base.Strings") 315 .log(WARNING, "Exception during lenientFormat for " + objectToString, e); 316 return "<" + objectToString + " threw " + e.getClass().getName() + ">"; 317 } 318 } 319}