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