⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stringutil.java

📁 google的gdata api包
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
  public static String stripPrefix(String str, String prefix) {    return str.startsWith(prefix) ? str.substring(prefix.length()) : null;  }  /**   * Case insensitive version of stripPrefix.   * Analogous to the c++ functions strcaseprefix and var_strcaseprefix.   */  public static String stripPrefixIgnoreCase(String str, String prefix) {    if (str.length() >= prefix.length()        && str.substring(0, prefix.length()).equalsIgnoreCase(prefix)) {      return str.substring(prefix.length());    }    return null;  }  /**   * Strips all non-digit characters from a string.   *   * The resulting string will only contain characters for which isDigit()   * returns true.   *   * @param str the string to strip   * @return a string consisting of digits only, or an empty string   */  public static String stripNonDigits(String str) {    StringBuffer result = new StringBuffer(str.length());    for (char candidate : str.toCharArray()) {      if (Character.isDigit(candidate)) {        result.append(candidate);      }    }    return result.toString();  }  /**   * Counts the number of (not necessarily distinct) characters in the   * string that also happen to be in 'chars'   */  public static int numSharedChars(final String str, final String chars) {    if (str == null || chars == null) {      return 0;    }    int total = 0, pos = -1;    while ((pos = indexOfChars(str, chars, pos + 1)) != -1) {      total++;    }    return total;  }  /**   * Like String.indexOf() except that it will look for any of the   * characters in 'chars' (similar to C's strpbrk)   */  public static int indexOfChars(String str, String chars, int fromIndex) {    final int len = str.length();    for (int pos = fromIndex; pos < len; pos++) {      if (chars.indexOf(str.charAt(pos)) >= 0) {        return pos;      }    }    return -1;  }  /**   * Like String.indexOf() except that it will look for any of the   * characters in 'chars' (similar to C's strpbrk)   */  public static int indexOfChars(String str, String chars) {    return indexOfChars(str, chars, 0);  }  /**   * Finds the last index in str of a character not in the characters   * in 'chars' (similar to ANSI string.find_last_not_of).   *   * Returns -1 if no such character can be found.   */  public static int lastIndexNotOf(String str, String chars, int fromIndex) {    fromIndex = Math.min(fromIndex, str.length() - 1);    for (int pos = fromIndex; pos >= 0; pos--) {      if (chars.indexOf(str.charAt(pos)) < 0) {        return pos;      }    }    return -1;  }  /**   * Like String.replace() except that it accepts any number of old chars.   * Replaces any occurrances of 'oldchars' in 'str' with 'newchar'.   * Example: replaceChars("Hello, world!", "H,!", ' ') returns " ello  world "   */  public static String replaceChars(String str, String oldchars, char newchar) {    int pos = indexOfChars(str, oldchars);    if (pos == -1) {      return str;    }    StringBuilder buf = new StringBuilder(str);    do {      buf.setCharAt(pos, newchar);      pos = indexOfChars(str, oldchars, pos + 1);    } while (pos != -1);    return buf.toString();  }  /**   * Remove any occurrances of 'oldchars' in 'str'.   * Example: removeChars("Hello, world!", ",!") returns "Hello world"   */  public static String removeChars(String str, String oldchars) {    int pos = indexOfChars(str, oldchars);    if (pos == -1) {      return str;    }    StringBuilder buf = new StringBuilder();    int start = 0;    do {      buf.append(str.substring(start, pos));      start = pos + 1;      pos = indexOfChars(str, oldchars, start);    } while (pos != -1);    if (start < str.length()) {      buf.append(str.substring(start));    }    return buf.toString();  }  /**   * Removes all characters from 'str' that are not in 'retainChars'.   * Example: retainAllChars("Hello, world!", "lo") returns "llool"   */  public static String retainAllChars(String str, String retainChars) {    int pos = indexOfChars(str, retainChars);    if (pos == -1) {      return "";    }    StringBuilder buf = new StringBuilder();    do {      buf.append(str.charAt(pos));      pos = indexOfChars(str, retainChars, pos + 1);    } while (pos != -1);    return buf.toString();  }  /**   * Replaces microsoft "smart quotes" (curly " and ') with their   * ascii counterparts.   */  public static String replaceSmartQuotes(String str) {    // See http://www.microsoft.com/typography/unicode/1252.htm    str = replaceChars(str, "\u0091\u0092\u2018\u2019", '\'');    str = replaceChars(str, "\u0093\u0094\u201c\u201d", '"');    return str;  }  /**   * Convert a string of hex digits to a byte array, with the first   * byte in the array being the MSB. The string passed in should be   * just the raw digits (upper or lower case), with no leading   * or trailing characters (like '0x' or 'h').   * An odd number of characters is supported.   * If the string is empty, an empty array will be returned.   *   * This is significantly faster than using   *   new BigInteger(str, 16).toByteArray();   * especially with larger strings. Here are the results of some   * microbenchmarks done on a P4 2.8GHz 2GB RAM running   * linux 2.4.22-gg11 and JDK 1.5 with an optimized build:   *   * String length        hexToBytes (usec)   BigInteger   * -----------------------------------------------------   * 16                       0.570                 1.43   * 256                      8.21                 44.4   * 1024                    32.8                 526   * 16384                  546                121000   */  public static byte[] hexToBytes(String str) {    byte[] bytes = new byte[(str.length() + 1) / 2];    if (str.length() == 0) {      return bytes;    }    bytes[0] = 0;    int nibbleIdx = (str.length() % 2);    for (int i = 0; i < str.length(); i++) {      char c = str.charAt(i);      if (!isHex(c)) {        throw new IllegalArgumentException("string contains non-hex chars");      }      if ((nibbleIdx % 2) == 0) {        bytes[nibbleIdx >> 1] = (byte) (hexValue(c) << 4);      } else {        bytes[nibbleIdx >> 1] += (byte) hexValue(c);      }      nibbleIdx++;    }    return bytes;  }  /**   * Converts any instances of "\r" or "\r\n" style EOLs into "\n" (Line Feed).   */  public static String convertEOLToLF(String input) {    StringBuilder res = new StringBuilder(input.length());    char[] s = input.toCharArray();    int from = 0;    final int end = s.length;    for (int i = 0; i < end; i++) {      if (s[i] == '\r') {        res.append(s, from, i - from);        res.append('\n');        if (i + 1 < end && s[i + 1] == '\n') {          i++;        }        from = i + 1;      }    }    if (from == 0) {   // no \r!      return input;    }    res.append(s, from, end - from);    return res.toString();  }  /** @deprecated Please inline this method. */  @Deprecated public static String convertEOLToCRLF(String input) {    return input.replaceAll("(\r\n|\r|\n)", "\r\n");  }  /**   * Returns a string consisting of "s", plus enough copies of "pad_ch" on the   * left hand side to make the length of "s" equal to or greater than len (if   * "s" is already longer than "len", then "s" is returned).   */  public static String padLeft(String s, int len, char pad_ch) {    if (s.length() >= len) {      return s;    } else {      StringBuilder sb = new StringBuilder();      int n = len - s.length();      for (int i = 0; i < n; i++) {        sb.append(pad_ch);      }      sb.append(s);      return sb.toString();    }  }  /**   * Returns a string consisting of "s", plus enough copies of "pad_ch" on the   * right hand side to make the length of "s" equal to or greater than len (if   * "s" is already longer than "len", then "s" is returned).   */  public static String padRight(String s, int len, char pad_ch) {    if (s.length() >= len) {      return s;    } else {      StringBuilder sb = new StringBuilder();      int n = len - s.length();      sb.append(s);      for (int i = 0; i < n; i++) {        sb.append(pad_ch);      }      return sb.toString();    }  }  /**   * Returns a string consisting of "s", with each of the first "len" characters   * replaced by "mask_ch" character.   */  public static String maskLeft(String s, int len, char mask_ch) {    if (len <= 0) {      return s;    }    len = Math.min(len, s.length());    StringBuilder sb = new StringBuilder();    for (int i = 0; i < len; i++) {      sb.append(mask_ch);    }    sb.append(s.substring(len));    return sb.toString();  }  /**   * Returns a string consisting of "s", with each of the last "len" characters   * replaces by "mask_ch" character.   */  public static String maskRight(String s, int len, char mask_ch) {    if (len <= 0) {      return s;    }    len = Math.min(len, s.length());    StringBuilder sb = new StringBuilder();    sb.append(s.substring(0, s.length() - len));    for (int i = 0; i < len; i++) {      sb.append(mask_ch);    }    return sb.toString();  }  private static boolean isOctal(char c) {    return (c >= '0') && (c <= '7');  }  private static boolean isHex(char c) {    return ((c >= '0') && (c <= '9')) ||           ((c >= 'a') && (c <= 'f')) ||           ((c >= 'A') && (c <= 'F'));  }  private static int hexValue(char c) {    if ((c >= '0') && (c <= '9')) {      return (c - '0');    } else if ((c >= 'a') && (c <= 'f')) {      return (c - 'a') + 10;    } else {      return (c - 'A') + 10;    }  }  /**   * Unescape any C escape sequences (\n, \r, \\, \ooo, etc) and return the   * resulting string.   */  public static String unescapeCString(String s) {    if (s.indexOf('\\') < 0) {      // Fast path: nothing to unescape      return s;    }    StringBuilder sb = new StringBuilder();    int len = s.length();    for (int i = 0; i < len;) {      char c = s.charAt(i++);      if (c == '\\' && (i < len)) {        c = s.charAt(i++);        switch (c) {          case 'a':  c = '\007';  break;          case 'b':  c = '\b';    break;          case 'f':  c = '\f';    break;          case 'n':  c = '\n';    break;          case 'r':  c = '\r';    break;          case 't':  c = '\t';    break;          case 'v':  c = '\013';  break;          case '\\': c = '\\';    break;          case '?':  c = '?';     break;          case '\'': c = '\'';    break;          case '"':  c = '\"';    break;          default: {            if ((c == 'x') && (i < len) && isHex(s.charAt(i))) {              // "\xXX"              int v = hexValue(s.charAt(i++));              if ((i < len) && isHex(s.charAt(i))) {                v = v*16 + hexValue(s.charAt(i++));              }              c = (char)v;            } else if (isOctal(c)) {              // "\OOO"              int v = (c - '0');              if ((i < len) && isOctal(s.charAt(i))) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -