|
| 1 | +package util; |
| 2 | + |
| 3 | +import java.util.Random; |
| 4 | + |
| 5 | +/** |
| 6 | + * Util for String |
| 7 | + * |
| 8 | + * @author liu yuning |
| 9 | + * |
| 10 | + */ |
| 11 | +public class StringUtil { |
| 12 | + |
| 13 | + private static final int DEFAULT_STRING_LENGTH = 10; |
| 14 | + |
| 15 | + private static final String LETTERS = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
| 16 | + |
| 17 | + private static Random random = new Random(); |
| 18 | + |
| 19 | + /** |
| 20 | + * Don't let anyone instantiate this class. |
| 21 | + */ |
| 22 | + private StringUtil() { |
| 23 | + |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * |
| 28 | + * @param str |
| 29 | + * @return {@code true} if the input {@code String} is null or "" |
| 30 | + */ |
| 31 | + public static boolean empty(final String str) { |
| 32 | + return str == null || str.trim().isEmpty(); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * generate random string |
| 37 | + * |
| 38 | + * @return a random string |
| 39 | + */ |
| 40 | + public static String generateRandomString() { |
| 41 | + return generateRandomString(DEFAULT_STRING_LENGTH); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * generate random string using all letters and the given length |
| 46 | + * |
| 47 | + * @param stringLength |
| 48 | + * @return a random string |
| 49 | + */ |
| 50 | + public static String generateRandomString(int stringLength) { |
| 51 | + if (stringLength <= 0) { |
| 52 | + stringLength = DEFAULT_STRING_LENGTH; |
| 53 | + } |
| 54 | + |
| 55 | + StringBuilder stringBuilder = new StringBuilder(); |
| 56 | + |
| 57 | + for (int i = 0; i < stringLength; i++) { |
| 58 | + stringBuilder |
| 59 | + .append(LETTERS.charAt(random.nextInt(LETTERS.length()))); |
| 60 | + } |
| 61 | + |
| 62 | + return stringBuilder.toString(); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * repeat a {@code String} called repeatStr for repeatNum times |
| 67 | + * |
| 68 | + * @param repeatStr |
| 69 | + * @param repeatNum |
| 70 | + * @return {@code String} repeatedString |
| 71 | + */ |
| 72 | + public static String repeatableString(String repeatStr, int repeatNum) { |
| 73 | + StringBuilder stringBuilder = new StringBuilder(); |
| 74 | + |
| 75 | + while (repeatNum-- > 0) { |
| 76 | + stringBuilder.append(repeatStr); |
| 77 | + } |
| 78 | + |
| 79 | + return stringBuilder.toString(); |
| 80 | + } |
| 81 | + |
| 82 | +} |
0 commit comments