📄 strings.java
字号:
} else if (handleQuotation && (cc == '\'' || cc == '"')) { return from; } if (isSeparator(cc, separators)) return from; } return from; } private static final boolean isSeparator(char cc, char[] separators) { for (int j = 0; j < separators.length; ++j) { if (cc == separators[j] || (separators[j] == ' ' && Character.isWhitespace(cc))) return true; } return false; } /** The result of {@link #substring}. */ public static class Result { /** The next index. */ public int next; /** The converted string. */ public String token; /** The separator found. If no separator but end-of-line found, * ((char)0) is returned. */ public char separator; protected Result(int next, String token, char separator) { this.next = next; this.token = token; this.separator = separator; } protected Result(int next, char separator) { this.next = next; this.separator = separator; } //-- Object --// public String toString() { return "[next="+next+", token="+token+" separator="+separator+']'; } } /** * Remove the suffix if a string ends with the specified suffix. * If not found, the original string is returned * * @param s the string to process * @param suffix the suffix to remove * @return the processed string * @see #removePrefix(String, String) */ public final static String removeSuffix(String s, String suffix) { return s.endsWith(suffix) ? s.substring(0, s.length() - suffix.length()) : s; } /** * Remove the prefix if a string starts with the specified prefix. * * @param s the string to process * @param prefix the prefix to remove * @return the processed string * @see #removeSuffix(String, String) */ public final static String removePrefix(String s, String prefix) { return s.startsWith(prefix) ? s.substring(prefix.length()) : s; } /** * Removes the prefix upto the last separator (excluding). * It is the same as * to getSuffix if the string contains the separator. However, * if the separator is not contained, it returns the whole string * while getSuffix returns null. * * <p><code>Strings.removeUptoLast("/home/java/file", '/');</code><br> * returns "file" * * @param s the string to process * @param sep the separator * @return the rest part; s if separator not found * @see #getSuffix * @see #removeSinceLast */ public final static String removeUptoLast(String s, char sep) { int j = s.lastIndexOf(sep); return j<0 ? s: s.substring(j+1); } /** * Remove the suffix since the last separator (excluding). * * <p><code>Strings.removeUptoLast("/home/java/file", '/');</code><br> * returns "/home/java" * * @param s the string to process * @param sep the separator * @return the rest part; s if separator not found * @see #getPrefix * @see #removeUptoLast */ public final static String removeSinceLast(String s, char sep) { int j = s.lastIndexOf(sep); return j<0 ? s: s.substring(0, j); } /** * Gets the suffix after the last separator. * If specifying the separator to '.', caller could get * the last element of a Java class name. * * <p>Strings.getSuffix("abc.def.xyz", '.');<br> * //returns "xyz" * * @param s the string to process * @param sep the separator * @return the suffix; null if separator not found * @see #removeUptoLast */ public final static String getSuffix(String s, char sep) { int j = s.lastIndexOf(sep); return j<0 || (j+1) >= s.length() ? null: s.substring(j+1); } /** * Gets the prefix before (exclude) the last separator. * If specifying the separator to '.', caller could get * the package name of a Java class name. * * <p>Strings.getPrefix("abc.def.xyz", '.');<br> * //returns "abc.def" * * @param s the string to process * @param sep the separator * @return the prefix; the string if separator not found */ public final static String getPrefix(String s, char sep) { int j = s.lastIndexOf(sep); return j<0 ? s : s.substring(0, j); } /** * Gets the prefix before (exclude) the first separator. * * <p>Strings.getShortestPrefix("abc.def.xyz", '.');<br> * //returns "abc" * * @param s the string to process * @param sep the separator * @return the prefix; the string if separator not found */ public final static String getShortestPrefix(String s, char sep) { int j = s.indexOf(sep); return j<0 ? s : s.substring(0, j); } /** * Capitalizes the j-th letter of a string. * * @param s the string to process * @param j the letter to capitalize; 0 for the first * @return the capitalized string * @see #uncapitalize */ public final static String capitalize(String s, int j) { if (s.length() <= j || Character.isUpperCase(s.charAt(j))) return s; //we don't use substring due to the performance issue final char[] buf = s.toCharArray(); buf[j] = Character.toUpperCase(buf[j]); return new String(buf); } /** * Un-capitalizes the j-th letter of a string. * * @param s the string to process * @param j the letter to capitalize; 0 for the first * @return the uncapitalized string * @see #capitalize */ public final static String uncapitalize(String s, int j) { if (s.length() <= j || Character.isLowerCase(s.charAt(j))) return s; //we don't use substring due to the performance issue final char[] buf = s.toCharArray(); buf[j] = Character.toLowerCase(buf[j]); return new String(buf); } /** * Gets the number of occurrences of the giving character. * @param s the string; null is acceptable */ public final static int getOccurrences(String s, char c) { int cnt = 0; int len = s!=null ? s.length(): 0; for (int j=0; j<len; ++j) if (s.charAt(j) == c) ++cnt; return cnt; } /** Normalizes a string. It removes all surrounding whitespace * and merges consecutive spaces to one. Also, '\r' and '\n' * are converted to space. */ public static final String normalize(String s) { final int len = s.length(); final char[] dst = new char[len]; boolean white = true; boolean modified = false; int pos = 0; for (int j = 0; j < len; j++) { final char cc = s.charAt(j); if (" \t\n\r".indexOf(cc) >= 0) { if (!white) { dst[pos++] = ' '; white = true; if (cc != ' ') modified = true; } } else { dst[pos++] = cc; white = false; } } if (white && pos > 0) pos--; return !modified && pos==s.length() ? s: new String(dst, 0, pos); } /** Converts a string by processing back-slashes. * * <p>They include \\u, \n, \r, \f, \t. */ public static final String convertBackslash(String src) { char cc; int len = src.length(); StringBuffer sb = new StringBuffer(len); for (int j = 0; j < len; ) { cc = src.charAt(j++); if (cc == '\\') { cc = src.charAt(j++); if (cc == 'u') { int value = 0; for (int k = 0; k < 4; k++) { cc = src.charAt(j++); if (cc >= '0' && cc <= '9') value = (value << 4) + cc - '0'; else if (cc >= 'a' && cc <= 'f') value = (value << 4) + 10 + cc - 'a'; else if (cc >= 'A' && cc <= 'F') value = (value << 4) + 10 + cc - 'A'; else throw new IllegalArgumentException( "Malformed \\uxxxx encoding."); } sb.append((char)value); } else { if (cc == 't') cc = '\t'; else if (cc == 'r') cc = '\r'; else if (cc == 'n') cc = '\n'; else if (cc == 'f') cc = '\f'; sb.append(cc); } } else { sb.append(cc); } } return sb.toString(); } /** * Converts a string to an object with the specified type. * It handles primitive types, Date, the enumeration type, and * class with a constructor that accepts String as the argument. * * <p>If str is null and type is not a primitive, null is returned. * * @param type the type of the primitive (can be the primitive or the * wrapper class), or the enumeration type * @param str the String representation of the primitive * @return the object being converted * * @exception NumberFormatException if it failed to convert to a number * @exception ParseException if it failed to convert to a Date * @exception NoSuchMethodException if the class has no constructor * accepting a string argument */ public static final Object toObject(Class type, String str) throws NoSuchMethodException, InstantiationException, ParseException, IllegalAccessException, InvocationTargetException { return _objtz.toObject(type, str); } /** Sets the objectizer which is used to convert a string to an object. * * @param objtz the new objectizer. If null is specified, the default * one is used. * @return the previous objectizer (never null). */ public static final Objectizer setObjectizer(Objectizer objtz) { final Objectizer old = _objtz; _objtz = objtz != null ? objtz: newDefaultObjectizer(); return old; } private static Objectizer _objtz = newDefaultObjectizer(); /** Defines the method used to convert a string to an object. */ public static interface Objectizer { /** Convers a string to an object of the specified type. */ public Object toObject(Class type, String str) throws NoSuchMethodException, InstantiationException, ParseException, IllegalAccessException, InvocationTargetException; } private static Objectizer newDefaultObjectizer() { return new Objectizer() { public Object toObject(Class type, String str) throws NoSuchMethodException, InstantiationException, ParseException, IllegalAccessException, InvocationTargetException { if (str == null && !type.isPrimitive()) { return null; } else if (String.class == type) { return str; } else if (char[].class == type) { return str.toCharArray(); } else if (Boolean.class == type || Boolean.TYPE == type) { return Boolean.valueOf(str); } else if (Byte.class == type || Byte.TYPE == type) { return Byte.valueOf(trimForDigits(str)); } else if (Character.class == type || Character.TYPE == type) { return new Character(str.charAt(0)); } else if (Short.class == type || Short.TYPE == type) { return Short.valueOf(trimForDigits(str)); } else if (Integer.class == type || Integer.TYPE == type) { return Integer.valueOf(trimForDigits(str)); } else if (Long.class == type || Long.TYPE == type) { return Long.valueOf(trimForDigits(str)); } else if (Float.class == type || Float.TYPE == type) { return Float.valueOf(str.trim()); //don't use trimForDigit because it cannot handle 1e-1 } else if (Double.class == type || Double.TYPE == type) { return Double.valueOf(str.trim()); //don't use trimForDigit because it cannot handle 1e-1 } else if (Date.class == type) { return DateFormats.parse(str); } else if (BigDecimal.class == type) { return new BigDecimal(trimForDigits(str)); } else if (BigInteger.class == type) { return new BigInteger(trimForDigits(str)); } else if (Locale.class == type) { return Locales.getLocale(str, (char)0); } else if (TimeZone.class == type) { return TimeZone.getTimeZone(str); } else { return type.getConstructor(new Class[] {String.class}) .newInstance(new Object[] {str}); } } }; } /** * Trim away the non digits character in the specified string. Generally * used to trim away the thousand seperators or monetary prefix or postfix. * E.g. NT$123,456,789.12 -> 123456789.12 */ private static final String trimForDigits(String str) { final int len = str.length(); final StringBuffer sb = new StringBuffer(len); for (int j = 0; j < len; j++) { final char cc = str.charAt(j); if (Character.isDigit(cc) || cc == '.' || cc == '-') sb.append(cc); } return sb.toString(); } /** * Prefix a specified String with a prefix String and delimited with the * specified delimeter; however, if prefix is empty or null or the given * string is null, this method would simply return the original String. */ public static final String prefix(String str, String pre, char delimiter) { if (str == null || pre == null || pre.length() == 0) return str; return pre + delimiter + str; } /** Advanced ID to the next. * Example, advance("R012", 2) returns "R015". */ public static final String advance(String id, int step) { final int len = id.length(); int j = len; while (--j >= 0) { final char cc = id.charAt(j); if (cc < '0' || cc > '9') break; } final int val; int digits = len - ++j; if (digits == 0) { val = 0; digits = 2; } else { val = Integer.parseInt(id.substring(j)); } return id.substring(0, j) + Integers.toStringByScale(val + step, digits); } /** * Make the number of n characters. */ public static final String nStrings(int n, String str) { final StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) sb.append( str ); return sb.toString(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -